sparkandshine sparkandshine - 1 year ago 44
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

, into

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

What does Python interpreter do, like this?

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

Answer Source

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 '