这里我用下划线替换了空格,但是我无法用空格替换下划线
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.
答案 0 :(得分:4)
您可以使用meta-linaro
一次替换多个(单个字符)元素:
以您的示例为例:
str.translate
输出:
s = 'this is an __example__'
translate_table = str.maketrans({' ': '_', '_': ' '})
print(s.translate(translate_table))
答案 1 :(得分:2)
如何?
mystr = 'But I want_to bring_out something_that we_are back to stay.'
mystr.replace(' ', '$').replace('_', ' ').replace('$', '_')
# 'But_I_want to_bring out_something that_we are_back_to_stay.'
我使用了$
,但请确保使用不会在您的输入中出现的字符。
编辑
或者您可以将maketrans与translate结合使用:
trans = str.maketrans({' ': '_', '_': ' '})
mystr.translate(trans)
# 'But_I_want to_bring out_something that_we are_back_to_stay.'
答案 2 :(得分:0)
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()
语法,请使用m[0]