Pavlos Pavlos - 1 year ago 82
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.

Answer Source

Use Regular Expressions.


import re

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

Here is the Python tutorial.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download