2024-09-30 00:23:04 发布
网友
这有可能吗?在
基本上,我想将这两个调用转换为一个单独的调用:
re.sub(r'\bAword\b', 'Bword', mystring) re.sub(r'\baword\b', 'bword', mystring)
我真正想要的是某种条件替换符号,比如:
我只关心第一个字符的大写。其他人都没有。在
您可以使用函数来分析每个匹配项:
>>> def f(match): return chr(ord(match.group(0)[0]) + 1) + match.group(0)[1:] >>> re.sub(r'\b[aA]word\b', f, 'aword Aword') 'bword Bword'
可以传递使用Match对象作为参数的lambda函数作为替换函数:
import re re.sub(r'\baword\b', lambda m: m.group(0)[0].lower() == m.group(0)[0] and 'bword' or 'Bword', 'Aword aword', flags=re.I) # returns: 'Bword bword'
好的,这是我想出的解决方案,多亏了使用replace函数的建议。在
re.sub(r'\b[Aa]word\b', lambda x: ('B' if x.group()[0].isupper() else 'b') + 'word', 'Aword aword.')
您可以使用函数来分析每个匹配项:
可以传递使用Match对象作为参数的lambda函数作为替换函数:
好的,这是我想出的解决方案,多亏了使用replace函数的建议。在
相关问题 更多 >
编程相关推荐