How to convert a string to an int in Python
Call int(s). It accepts leading/trailing whitespace and raises ValueError on anything that isn't a valid integer.
s = "42"
n = int(s)
print(n + 8) # 50int() accepts a str and returns the integer it represents. Whitespace around the digits is stripped; a leading '+' or '-' is honoured; embedded whitespace or letters raise ValueError.
For bases other than 10, pass the base as the second argument: int('ff', 16) β 255, int('101', 2) β 5. This is how you parse hex or binary from a string.
If you have a string that MIGHT be a number, wrap the call in try/except ValueError β Python has no 'is_integer' equivalent to JavaScript's Number.isInteger() for strings.
Variations
Parse hexadecimal
n = int("ff", 16) # 255
n = int("0xff", 16) # also 255Base can be 2 (binary), 8 (octal), 10 (decimal), 16 (hex), or 0 (auto-detect from prefix).
Safe parse with default
def to_int(s, default=0):
try:
return int(s)
except (ValueError, TypeError):
return defaultHandles both non-numeric strings and None.
Float to int (truncates)
int(3.7) # 3
int(-3.7) # -3 (toward zero, not floor)Use math.floor() if you want -3.7 β -4.
Get one Python lesson + one career idea every Friday
No spam, no "buy our course now". Three bullets, every Friday. Unsubscribe with one click.