Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python print string like a raw string

Tags:

python

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?

like image 658
Haoliang Avatar asked Oct 23 '14 01:10

Haoliang


People also ask

How do you convert a string to a raw string in Python?

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.

How do you get a raw string in Python?

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.

How can we make a string tab a raw string?

To make a string to raw string we have to add "R" before the string.

What does %S and %D do in Python?

They are used for formatting strings. %s acts a placeholder for a string while %d acts as a placeholder for a number.


2 Answers

print(repr('a\tb')) 

repr() gives you the "representation" of the string rather than the printing the string directly.

like image 191
John Zwinck Avatar answered Oct 07 '22 17:10

John Zwinck


1:

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

2:

(Python 3)

print('a\\tb')  

3:

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}')) + 
like image 20
wyz23x2 Avatar answered Oct 07 '22 17:10

wyz23x2