Pradyumna
Pradyumna

Reputation: 167

Print confusion

I am new to python when i try to print "\20%" that is

>>>"\20%"

why is the shell printing '\x10%' that is, it is showing

'\x10%'

the same is happening with join also when is do

>>>l = ['test','case']
>>>"\20%".join(l)

it shows

'test\x10%case'

I am using python 2.7.3

Upvotes: 5

Views: 979

Answers (3)

Grijesh Chauhan
Grijesh Chauhan

Reputation: 58251

Two print "\20%"

what if you print directly:

>>> print '\20%'
%                       # some symbol not correctly display on this page

and do using r

>>> print r'\20%'
\20%
>>> r'\20%'         # what r do.
'\\20%'
>>> print '\\20%'     
\20%
>>> 

Some time back I had same doubt about string and I asked a question, you may find helpful

Upvotes: 1

user4815162342
user4815162342

Reputation: 154836

\20 is an escape sequence that refers to the DLE ASCII character whose decimal value is 16 (20 in octal, 10 in hexadecimal). Such a character is printed as the \x10 hex escape by the repr function of strings.

To specify a literal \20, either double the backslash ("\\20") or use a raw string (r"\20").

Upvotes: 2

phihag
phihag

Reputation: 287755

'\20' is an octal literal, and the same as chr(2 * 8 + 0) == chr(16).

What the Python shell displays by default is not the output of print, but the representation of the given value, which is the hexadecimal '\x10'.

If you want the string \20%, you have to either escape the backaslash ('\\20%') or use a raw string literal (r'\20%'). Both will be displayed as

>>> r'\20%'
'\\20%'

Upvotes: 11

Related Questions