在这里,我代替空格与下划线,但我不能够代替下划线与空间。
import re
def repl(string):
pattern = re.compile(' ')
match = pattern.search(string)
new_str = pattern.sub('_', string)
print(new_str)
repl('But I want_to bring_out something_that we_are back to stay.')
输出: But_I_want_to_bring_out_something_that_we_are_back_to_stay.
str.translate
如其他答案中所述,这里是单字符交换的最佳选择。
如果需要多字符字符串交换,则可以通过函数的替换部分中的函数调用来使用字典。 re.sub
>>> import re
>>> s = 'But I want_to bring_out something_that we_are back to stay.'
>>> d = {' ' : '_', '_' : ' '}
>>> re.sub(r'[ _]', lambda m: d[m[0]], s)
'But_I_want to_bring out_something that_we are_back_to_stay.'
m.group()
,如果你的Python版本不支持m[0]
的语法本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句