How do I convert a string to a number in Python?
Short answer
Use int for whole numbers and float for decimals. int rejects a string with a decimal point, so convert to float first, and wrap the conversion in try/except to handle input that is not a number.
The short version
Use int("42") for whole numbers and float("3.14") for decimals. A common trap is that int("3.14") raises an error, because int will not parse a decimal point directly; convert to float first if the text might contain one. Wrap the conversion in try/except ValueError to handle input that is not a valid number.
The basic conversions
int("42") # 42
float("3.14") # 3.14
Both ignore surrounding whitespace, so int(" 42 ") works, but neither accepts other stray characters.
The decimal-point trap
int("3.14") # ValueError: invalid literal for int() with base 10
int only parses whole numbers, so a decimal string fails. If you want the whole-number part of a decimal string, go through float first.
int(float("3.14")) # 3, the integer part
Note this truncates towards zero rather than rounding, so int(float("3.99")) is 3, not 4. Use round if you want rounding.
Handling bad input
Real input is not always a clean number, so guard the conversion.
text = "not a number"
try:
value = int(text)
except ValueError:
value = 0 # or handle it however suits
Catching ValueError lets you decide what to do with unparseable input, rather than letting the program crash. This matters whenever the string comes from a user or a file.
Other bases
int accepts a base for parsing binary, octal or hexadecimal strings, which is easy to forget.
int("ff", 16) # 255, hexadecimal
int("101", 2) # 5, binary
The default base is 10, so you only need this when the text represents a number in another base.
The reverse direction
To go from a number back to a string, use str or an f-string, which is handy for building messages.
str(42) # "42"
f"total is {42}" # "total is 42"
A note on whole columns
If you are converting a whole column of a DataFrame rather than a single value, do not loop with int. Use pd.to_numeric, which is vectorised and can turn unparseable entries into missing values with errors="coerce", so one bad row does not stop the whole conversion.