gpt4 book ai didi

python - 在python 3中用子字符串替换单个字符

转载 作者:太空宇宙 更新时间:2023-11-03 16:43:50 24 4
gpt4 key购买 nike

我试图用字符串替换任何不是:(字母、'.'、'_'、'-')的字符,但是 re.sub 总是替换整个字符串,而不仅仅是替换一个字符。

xmlreplace=re.compile("((?i)[^\w\_\-\.])", re.UNICODE)
print(xmlreplace.sub("regex test","-"))

预期输出:“regex-test”

实际输出:“-”

最佳答案

这些论点是错误的。

>>> help(xmlreplace.sub)
Help on built-in function sub:

sub(...)
sub(repl, string[, count = 0]) --> newstring
Return the string obtained by replacing the leftmost non-overlapping
occurrences of pattern in string by the replacement repl.
>>> print(xmlreplace.sub("-", "regex test"))
regex-test

关于python - 在python 3中用子字符串替换单个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36530733/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com