sparkandshine sparkandshine - 6 months ago 9
Python Question

How does "int('5\r\n')" works in Python?

I learn of converting a string to an integer from Python: Convert a string to an integer. But I was still wondering how this works, casting a string consisting of a number following line breaks, like

'5\r\n'
, into
int
.

>>> int(' \r \n 5 \r \n ')
5


What does Python interpreter do, like this?

>>> s = ' \r \n 5 \r \n '
>>> new_s = s.strip()
>>> int(new_s)
5

Answer

Because the interpreter evaluates the whitespaces beforehand; int only gets the string 5:

In [137]: int(' \r \n 5 \r \n ')
Out[137]: 5

This won't work if you make the string raw, which will preserve the string as it is:

In [138]: int(r' \r \n 5 \r \n ')
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-138-bd46e2cccbca> in <module>()
----> 1 int(r' \r \n 5 \r \n ')

ValueError: invalid literal for int() with base 10: ' \\r \\n 5 \\r \\n '