在python3中用子字符串替换单个字符

2024-10-01 15:30:49 发布

您现在位置:Python中文网/ 问答频道 /正文

但是,我正在尝试用字符串替换任何不是:(字母、“.”、“&”的字符回复sub总是替换整个字符串而不是一个字符。你知道吗

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

预期输出:“regex test”

实际输出:“-”


Tags: 字符串testre字母unicode字符regexprint
2条回答

争论是无序的。应该是的

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

争论是错误的。你知道吗

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

相关问题 更多 >

    热门问题