如何用下划线替换空白,并用字符串的空白替换下划线?

时间:2020-01-13 13:57:35

标签: python regex

这里我用下划线替换了空格,但是我无法用空格替换下划线

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.

3 个答案:

答案 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.'

我使用了$,但请确保使用不会在您的输入中出现的字符。

编辑

或者您可以将maketranstranslate结合使用:

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.'
  • 在这里,匹配部分用作从字典中获取相应值的键
  • 如果您的Python版本不支持m.group()语法,请使用m[0]
相关问题