Pavlos Pavlos - 7 months ago 36
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

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


Use Regular Expressions.


import re

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

Here is the Python tutorial.