Pavlos Pavlos - 3 months ago 6
Python Question

Replacing different characters in Python

Suppose you have a string which you want to parse into a specific format. That means: replace all

' ', '.', '-', etc with '_'
.

I know that I could do this:

>s = "Hello----..... World"
>s = s.replace('-','_').replace('.', '_').replace(' ', '_')
>print s
>Hello_____________World


And get what I want. But, is there a cleaner way? A more
pythonic
way?
I tried parsing a list in to the first argument of replace, but that didn't work very well.

Answer

Use Regular Expressions.

Ex:

import re

s = "Hello----.....    World"
print(re.sub(r"[ .-]", "_", s))

Here is the Python tutorial.