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

时间:2014-02-18 16:09:48

标签: python string python-3.x replace

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

请帮助修复脚本

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

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

但是我收到了消息:

  

语法无效

3 个答案:

答案 0 :(得分:12)

您可以使用re.sub()

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

答案 1 :(得分:8)

您可以使用str.translatedictionary comprehension

>>> 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'
>>>

如果您使用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
>>>

答案 2 :(得分:3)

你可以做点什么:

>>> rep_chars = ['\\', '/', ':', '*', '?', '"', '<', '>', '|']
>>> name = "/:*?\"<>name"
>>> for char in rep_chars:
...     name = name.replace(char,'')
...
>>> name
'name'