Say I got a unicode string from json which is u'a\tb', if I print it , I will get a    b.But what I want now is print a string exactly as a\tb. How can I do it?
Convert normal strings to raw strings with repr()Use the built-in function repr() to convert normal strings into raw strings. The string returned by repr() has ' at the beginning and the end. Using slices, you can get the string equivalent to the raw string.
Python raw string is created by prefixing a string literal with 'r' or 'R'. Python raw string treats backslash (\) as a literal character. This is useful when we want to have a string that contains backslash and don't want it to be treated as an escape character.
To make a string to raw string we have to add "R" before the string.
They are used for formatting strings. %s acts a placeholder for a string while %d acts as a placeholder for a number.
print(repr('a\tb'))   repr() gives you the "representation" of the string rather than the printing the string directly.
(Python 2)
print ur'a\tb'  Note that in Python 3.x, u'' is equal to '', and the prefix ur is invalid.
 Python 3:
print(r'a\tb')  (Python 3)
print('a\\tb')   If you want to get the raw repr of an existing string, here is a small function: (Python 3.6+)
def raw(string: str, replace: bool = False) -> str:     """Returns the raw representation of a string. If replace is true, replace a single backslash's repr \\ with \."""     r = repr(string)[1:-1]  # Strip the quotes from representation     if replace:         r = r.replace('\\\\', '\\')     return r  Examples:
>>> print(raw('1234')) 1234 >>> print('\t\n'); print('='*10); print(raw('\t\n'))       ========== \t\n >>> print(raw('\r\\3')) \r\\3 >>> print(raw('\r\\3', True)) \r\3  Note this won't work for \N{...} Unicode escapes, only r'\N{...}' can. But I guess JSON doesn't have this :)
>>> print(raw('\N{PLUS SIGN}')) + 
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With