9

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

asked Feb 18, 2014 at 16:09
2
  • have a look at str.stranslate() Commented Feb 18, 2014 at 16:12
  • the invalid syntax error is coming from the first item in your list: '\'. Since it is an escape character you'd need to use '\\' Commented Feb 18, 2014 at 16:43

3 Answers 3

15

You can use re.sub():

import re
newName = re.sub('[\\\\/:*?"<>|]', 'special char', name)
answered Feb 18, 2014 at 16:11
11

You can use str.translate and a dictionary 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'
>>>

If you use timeit.timeit, you will see that this method is generally faster than the others supplied:

>>> 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
>>>
answered Feb 18, 2014 at 16:40
0
3

you could do something like:

>>> rep_chars = ['\\', '/', ':', '*', '?', '"', '<', '>', '|']
>>> name = "/:*?\"<>name"
>>> for char in rep_chars:
... name = name.replace(char,'')
...
>>> name
'name'
answered Feb 18, 2014 at 16:34

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.