mining mining - 2 months ago 8
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'.


All
'-'
should be replaced with
'\-'
and all
'_'
should be replaced into
'\_'
.

The following method is not working:

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

Answer

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

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

Note the difference of print vs repr:

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

Is equivalent to:

>>> print(repr("abc-ccd_2013".replace("-","\-").replace("_","\_")))
'abc\\-ccd\\_2013'
Comments