Short way to convert string to int

Solution 1:

my_input = int(my_input)

There is no shorter way than using the int function (as you mention)

Solution 2:

Maybe you were hoping for something like my_number = my_input.to_int. But it is not currently possible to do it natively. And funny enough, if you want to extract the integer part from a float-like string, you have to convert to float first, and then to int. Or else you get ValueError: invalid literal for int().

The robust way:

my_input = int(float(my_input))

For example:

>>> nb = "88.8"
>>> int(nb)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '88.8'
>>> int(float(nb))
88