how to replace multiple characters in a string?
16,997
Solution 1
You can use re.sub():
import re
newName = re.sub('[\\\\/:*?"<>|]', 'special char', name)
Solution 2
you could do something like:
>>> rep_chars = ['\\', '/', ':', '*', '?', '"', '<', '>', '|']
>>> name = "/:*?\"<>name"
>>> for char in rep_chars:
... name = name.replace(char,'')
...
>>> name
'name'
Author by
Sergey
"Пьёт, дебоширит, занимается каким-то абстрактным цинизмом"
Updated on July 21, 2022Comments
-
Sergey almost 2 years
how to replace multiple characters in a string?
please help to fix the script
I need to in the line "name" special characters have been replaced by the phrase "special char"
newName = replace(name, ['\', '/', ':', '*', '?', '"', '<', '>', '|'], 'special char')
but I get the message:
invalid syntax