mining
mining

Reputation: 3709

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'
    >>> 

Upvotes: 1

Views: 45

Answers (3)

Emil
Emil

Reputation: 735

This works. When printing raw string, '\' is replaced with '\\' so it does not interpret it as escape character used for e.g. endline character '\n', tab character '\t' and so on. Try command print str2 or print a1 and it will be fine.

Update: Even stackoverflow replaces '\\' with '\', so instead I have to type '\\\' (to type this I had to use 5 slashes) :D

Upvotes: 1

PJay
PJay

Reputation: 2807

You could also do the following :

str1 = 'abc-ccd_2013'
repl = ('-', '\-'), ('_', '\_')
print reduce(lambda a1, a2: a1.replace(*a2), repl, str1)

You will have to use the print function to get your desired result.

Upvotes: 0

Chris_Rands
Chris_Rands

Reputation: 41218

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'

Upvotes: 2

Related Questions