29

I usually do this to convert string to int:

my_input = int(my_input)

but I was wondering if there was a less clumsy way, because it feels kind of long.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Sam Banks
  • 423
  • 1
  • 4
  • 6
  • I can't imagine what a shorter version is supposed to look like, even in principle. Unless you want to rename `i = int` or something? But we have to use some kind of code (calling a function is as short as it gets), and we have to assign the value back (because strings are immutable). – Karl Knechtel Sep 08 '22 at 08:23

3 Answers3

36
my_input = int(my_input)

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

Boris Verkhovskiy
  • 14,854
  • 11
  • 100
  • 103
Gonzalo
  • 3,674
  • 2
  • 26
  • 28
5

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
Boris Verkhovskiy
  • 14,854
  • 11
  • 100
  • 103
biocyberman
  • 5,675
  • 8
  • 38
  • 50
4

If it is user input, chances are the user inputted a string. So better catch the exception as well with try:

user_input = '88.8'
try:
    user_input = int(float(user_input))
except:
    user_input = 0
print(user_input)
Boris Verkhovskiy
  • 14,854
  • 11
  • 100
  • 103