How to replace multiple characters in a string?

How to replace multiple characters in a string?

please help fix the script

I need the string "name" to replace special characters with the phrase "special char"

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

but I get a message:

invalid syntax

+7
python string replace
source share
3 answers

You can use re.sub () :

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

You can use str.translate and dictionary understanding :

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

If you use timeit.timeit , you will see that this method is usually faster than the rest:

 >>> 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 >>> 
+8
source share

you can do something like:

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

All Articles