我有一个输入,我需要用and替换&&
Note : &&作为左侧和右侧空格和输出也应包含带有and的左侧和右侧空格
Input :个
s = 'n && && && && && &&n'
My code :个
m=re.sub(r'\s[&&]\s', ' and ',s)
print(m)
My output :个
n && && && && && &&n
Expected output :个
n and and and and and &&n
我有一个输入,我需要用and替换&&
Note : &&作为左侧和右侧空格和输出也应包含带有and的左侧和右侧空格
Input :个
s = 'n && && && && && &&n'
My code :个
m=re.sub(r'\s[&&]\s', ' and ',s)
print(m)
My output :个
n && && && && && &&n
Expected output :个
n and and and and and &&n
我认为您需要空格的后视和前视表达式,这样匹配就不会重叠,因为re.sub()
将"返回通过用替换repl
替换string
中最左侧的非重叠出现的pattern
而获得的字符串".
有关这些表达式的解释,请参见here.
>>> import re
>>> s = 'n && && && && && &&n'
>>> m = re.sub(r'(?<=\s)&&(?=\s)', 'and', s)
>>> print(m)
n and and and and and &&n
如果你想在字符串的末尾或开头捕获&&
,那么按照附近@tim biegeleisen的建议使用\S
.