如何替换字符串中的多个字符?

Ser*_*gey 7 python string replace python-3.x

如何替换字符串中的多个字符?

请帮助修复脚本

我需要在行"name"中将特殊字符替换为短语"special char"

newName = replace(name, ['\', '/', ':', '*', '?', '"', '<', '>', '|'], 'special char')
Run Code Online (Sandbox Code Playgroud)

但我收到的消息是:

无效的语法

Mar*_*mro 12

你可以使用re.sub():

import re
newName = re.sub('[\\\\/:*?"<>|]', 'special char', name)
Run Code Online (Sandbox Code Playgroud)


iCo*_*dez 9

你可以使用str.translate字典理解:

>>> name = ":1?2/3<4|5"
>>> bad = ['\\', '/', ':', '*', '?', '"', '<', '>', '|']
>>> newName = name.translate({ord(c):'special char' for c in bad})
>>> newName
'special char1special char2special char3special char4special char5'
>>>
Run Code Online (Sandbox Code Playgroud)

如果您使用timeit.timeit,您将看到此方法通常比其他提供的方法更快:

>>> from timeit import timeit
>>> name = ":1?2/3<4|5"
>>> bad = ['\\', '/', ':', '*', '?', '"', '<', '>', '|']
>>>
>>> timeit("import re;re.sub('[\\/:*?\"<>|]', 'special char', name)", "from __main__ import name")
11.773986358601462
>>>
>>> timeit("for char in bad: name = name.replace(char, 'special char')", "from __main__ import name, bad")
9.943640323001944
>>>
>>> timeit("name.translate({ord(c):'special char' for c in bad})", "from __main__ import name, bad")
9.48467780122894
>>>
Run Code Online (Sandbox Code Playgroud)