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

时间:2016-04-10 14:02:46

标签: python regex python-3.x

我试图更换任何不属于的字符:(字母,'。',' _',' - ')通过一串字符,但是re.sub总是替换整个字符串而不是一个字符。

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

预期输出:"正则表达式测试"

实际输出:" - "

2 个答案:

答案 0 :(得分:1)

争论是错误的。

>>> 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

答案 1 :(得分:0)

参数是无序的。它应该是

print(xmlreplace.sub("-" , "regex test"))

<强> Ideone Demo

如果您愿意,可以使用re.sub()

re.sub(pattern, repl, string, count=0)

然后,它应该是

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