The int() function
text = "42"
number = int(text)
print(number + 8) # 50
Once converted, the value behaves like any other integer, so you can do arithmetic with it instead of string concatenation.
Convert from another base
print(int("ff", 16)) # 255
print(int("1010", 2)) # 10
The second argument tells Python the base of the text, which is handy for parsing hexadecimal or binary strings.
Handle text that is not a number
try:
number = int("abc")
except ValueError:
print("That is not a valid number.")
Wrapping the call in try/except stops a single bad value from crashing your program.
Common mistakes
- Trying to convert a decimal string directly.
int("3.5")fails — useint(float("3.5"))to get3. - Expecting commas to be ignored.
int("1,000")raises an error; remove the comma first withreplace.
Frequently asked questions
Why does int("3.5") fail?
Because int() only parses whole numbers. Convert the text to a float first and then to an int: int(float("3.5")), which gives 3.
How do I check if a string is a number first?
Use text.strip().isdigit() for plain positive integers, or simply try the conversion inside a try/except block.
Want to get comfortable with Python types and conversions? Work through our free Python course with a run-it-yourself editor.