使用replace()替换多个符号

时间:2016-12-14 18:15:17

标签: python replace

如何使用replace()方法替换多个符号?只用一个replace()可以做到这一点吗?还是有更好的方法吗?

符号可以是这样的,例如-+/'.&

4 个答案:

答案 0 :(得分:5)

您可以使用re.sub并将字符放在character class

import re
re.sub('[-+/\'.&]', replace_with, input)

答案 1 :(得分:2)

您可以使用str.join生成器表达式(不导入任何库)来执行此操作:

>>> symbols = '/-+*'
>>> replacewith = '.'
>>> my_text = '3 / 2 - 4 + 6 * 9'  # input string

#  replace char in string if symbol v
>>> ''.join(replacewith  if c in symbols else c for c in my_text)
'3 . 2 . 4 . 6 . 9'   # Output string with symbols replaced

答案 2 :(得分:1)

# '7' -> 'A', '8' -> 'B'
print('asdf7gh8jk'.replace('7', 'A').replace('8', 'B'))

答案 3 :(得分:1)

你只能做一个符号替换,你可以做的是创建旧的字符串和新的字符串列表并循环它们:

string = 'abc'
old = ['a', 'b', 'c']
new = ['A', 'B', 'C']
for o, n in zip(old, new):
    string = string.replace(o, n)

print string
>>> 'ABC'
相关问题