Aminah Nuraini Aminah Nuraini - 2 months ago 18
Python Question

Why does 11 not printed from a string in this Python script?

There is a Python question like this:

>>> import string
>>> s = ‘mary11had a little lamb’
>>> print s
mary had a little lamb


Actually when I try it myself, the result is not that, but:

mary11had a little lamb


Is there anything I don't know about Python that can make 11 disappear from a string?

Answer

As Padraic has pointed out in the comments - it looks like the leading backslash is missing before the 11 as a minor typo in the question.

So it should read

>>> import string
>>> s = ‘mary\11had a little lamb’
>>> print s
mary    had a little lamb

It's interpreting \11 as the escape sequence for a numerically defined ascii character, which in this case is horizontal tab (\t). As without qualification, \nnn is assumed to be octal (as opposed to \xnn which is interpreted as hexadecimal).

So if you were to write just >>> s in the REPL, you'd expect it to evaluate to 'mary\thad a little lamb'.

Same outcome if you entered: 'mary\x09had a little lamb'

Comments