Search code examples
pythonpython-2.7special-characters

Do not transform special characters in Python


I just want to print the original string.

[Case1] I know put "r" before the string can work

print r'123\r\n567"45'
>>`
123\r\n567"45

[Case2] But when it is a Variable

aaa = '123\r\n567"45'
print aaa
>>    
123
567"45

Is there any function can print aaa with the same effect like Case1?


Solution

  • The obvious way to make Case 2 work like Case 1 is to use a raw string in your assignment statement:

    aaa = r'123\r\n567"45'
    

    Now when you print aaa, you'll get the actual backslashes and r and n characters, rather than a carriage return and a newline.

    If you're actually loading aaa from some other source (rather than using a string literal), your task is a little bit more complicated. You'll actually need to transform the string in some way to get the output you want.

    One simple way of doing something close to what you want is to use the repr function:

    aaa = some_function() # returns '123\r\n567"45' and some_function can't be changed
    
    print repr(aaa)
    

    This will not quite do what you want though, since it will add quotation marks around the string's text. If you care about that, you could remove them with a slice:

    print repr(aaa)[1:-1]
    

    Another approach to take is to manually transform the characters you want escaped, e.g. with str.replace or str.translate. This is easy to do if you only care about escaping a few special characters and not others.

    print aaa.replace('\r', r'\r').replace('\n', r'\n')
    

    A final option is to use str.encode with the special character set called unicode-escape, which will escape all characters that are not printable ASCII:

    print aaa.encode('unicode-escape')
    

    This only works as intended in Python 2 however. In Python 3, str.encode always returns a bytes instance which you'd need to decode again to get a str (aaa.encode('unicode-escape').decode('ascii') would work, but it's really ugly).