mining mining - 1 year ago 68
Python Question

How to change a string into a formatted string?

I want to change a source string:

str1 = 'abc-ccd_2013'

into the following target string:

str2 = 'abc\-ccd\_2013'.

should be replaced with
and all
should be replaced into

The following method is not working:

>>> str1
>>> a1 = str1.replace("-","\\-")
>>> a1
>>> a1 = str1.replace("-","\-")
>>> a1
>>> a1 = str1.replace('-','\-')
>>> a1
>>> a1 = str1.replace(r'-',r'\-')
>>> a1

Answer Source

Your code does work and can be combined to a single expression:

>>> print("abc-ccd_2013".replace("-","\-").replace("_","\_"))

Note the difference of print vs repr:

>>> "abc-ccd_2013".replace("-","\-").replace("_","\_")

Is equivalent to:

>>> print(repr("abc-ccd_2013".replace("-","\-").replace("_","\_")))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download