在python中是否有一种简单的方法将多个字符替换为另一个字符?
例如,我想改变:
name1_22:3-3(+):Pos_bos 至
name1_22_3-3_+__Pos_bos因此,基本上将所有的"(",")",":"替换为"_"。
我只知道用:
str.replace(":","_")
str.replace(")","_")
str.replace("(","_")发布于 2019-03-21 13:14:30
另一种可能是使用所谓的列表理解与所谓的三值条件运算符相结合的方式如下:
text = 'name1_22:3-3(+):Pos_bos '
out = ''.join(['_' if i in ':)(' else i for i in text])
print(out) #name1_22_3-3_+__Pos_bos由于它给出了list,我使用''.join将字符的list (长度为1的strs)转换为str。
发布于 2019-03-21 12:48:29
使用翻译表。在Python2中,maketrans是在string模块中定义的。
>>> import string
>>> table = string.maketrans("():", "___")在Python3中,它是一个str类方法。
>>> table = str.maketrans("():", "___")在这两种情况下,表都作为参数传递给str.translate。
>>> 'name1_22:3-3(+):Pos_bos'.translate(table)
'name1_22_3-3_+__Pos_bos'在Python3中,还可以将单个dict映射输入字符传递到输出字符到maketrans。
table = str.maketrans({"(": "_", ")": "_", ":": "_"})发布于 2019-03-21 12:49:37
坚持当前使用replace()的方法
s = "name1_22:3-3(+):Pos_bos"
for e in ((":", "_"), ("(", "_"), (")", "__")):
s = s.replace(*e)
print(s)输出
name1_22_3-3_+___Pos_bos编辑:(用于可读性)
s = "name1_22:3-3(+):Pos_bos"
replaceList = [(":", "_"), ("(", "_"), (")", "__")]
for elem in replaceList:
print(*elem) # : _, ( _, ) __ (for each iteration)
s = s.replace(*elem)
print(s)或
repList = [':','(',')'] # list of all the chars to replace
rChar = '_' # the char to replace with
for elem in repList:
s = s.replace(elem, rChar)
print(s)https://stackoverflow.com/questions/55280595
复制相似问题