2016-12-14 191 views
4

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

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

+1

我认为,正则表达式会做最好 –

+0

取决于你想要什么,列表理解可以给字符串,例如单独的变种's ='GATCCAGATCCCCATAC','[s.replace(k,“Q”)for k in(“G”,“T”)]' – pylang

回答

1
# '7' -> 'A', '8' -> 'B' 
print('asdf7gh8jk'.replace('7', 'A').replace('8', 'B')) 
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' 
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 
+1

尽管're'受欢迎,但我觉得像这样的基因更像pythonic 。 – pylang