Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Can we convert a string to int or float?

  • isdigit
  • int
  • float

for var in ["23", "2.3", "a", "2.3.4", "2x"]:
    print(var)
    if var.isdigit():
        print(f"{var} can be converted to int:", int(var))
    if var.replace(".", "", 1).isdigit():
        print(f"{var} can be converted to float:", float(var))
    print('-----')




23
23 can be converted to int: 23
23 can be converted to float: 23.0
-----
2.3
2.3 can be converted to float: 2.3
-----
a
-----
2.3.4
-----
2x
-----