Python String to Int, Int to String
Guide: how to convert python string to int and python int to string safely using int(), str(), base parameter, and try/except.
Drake Nguyen
Founder · System Architect
Overview: python string to int and int to string
Converting between text and numbers is a common task in Python. This guide shows how to convert a python string to int and how to convert an int to a string using built-in functions, explains the int() base parameter, and demonstrates safe conversion patterns to avoid ValueError and other pitfalls.
Convert a simple string to an integer
Use python int() to turn a numeric string into an integer. This is the standard way to cast string to int python when the string represents a base-10 integer.
# basic conversion
num = '123'
print(type(num)) # <class 'str'>
num = int(num)
print(type(num)) # <class 'int'>
Using int() with a base: python string to int with base
The int() function accepts an optional base argument for converting strings that represent numbers in bases other than 10. Valid bases range from 2 to 36. The returned integer is always a Python int (base-10 representation).
# interpreting the same digits in different bases
s = '123'
print(int(s, base=10)) # 123 (decimal)
print(int(s, base=8)) # 83 (octal 123 -> decimal 83)
print(int('1010', base=2)) # 10 (binary)
print(int('1e', base=16)) # 30 (hexadecimal '1e' -> decimal 30)
Tip: int('FF', 16) and int('ff', 16) both work because int() accepts uppercase and lowercase letters for bases above 10.
Common errors: ValueError when converting string to int
ValueError occurs when the string does not represent a valid integer for the chosen base. Examples include non-digit characters when base is 10, or forgetting to supply base=16 for hexadecimal strings.
print(int('12a')) # ValueError: invalid literal for int() with base 10: '12a'
print(int('1e')) # ValueError in base 10 because 'e' is not a decimal digit
print(int('1e', base=16)) # works -> 30
Safely convert string to int: try/except and validation
To avoid runtime exceptions, validate input or use try/except. This is useful when parsing user input, reading files, or converting CSV values.
def safe_int(s, base=10, default=None):
try:
return int(s, base)
except (ValueError, TypeError):
return default
# examples
print(safe_int('42')) # 42
print(safe_int('1e', base=16)) # 30
print(safe_int('1e')) # None (invalid decimal)
You can also pre-process strings (strip whitespace, remove commas) or attempt float parsing for values like '12.0' before casting to int:
value = ' 12.0 '
try:
intval = int(value.strip())
except ValueError:
intval = int(float(value.strip())) # falls back to parsing as float then converting
print(intval) # 12
Parsing hex, binary and other bases
- Hexadecimal: int('ff', 16) -> 255
- Binary: int('1011', 2) -> 11
- Octal: int('17', 8) -> 15
Remember: the base parameter controls how the string is interpreted; the integer value returned is always a standard Python int.
Convert an int to a string: python int to string
Use python str() to convert numbers to their string form. This is useful for concatenation, formatting, or storing numbers as text.
n = 255
s = str(n)
print(type(n), type(s)) # <class 'int'> <class 'str'>
print(s) # '255' when inspected, printing shows 255 without quotes
Alternative formatting options include f-strings or format():
n = 42
print(f"Value: {n}")
print("Value: {}".format(n))
Quick checklist for robust python type conversion
- Use int() for converting numeric strings; supply base when working with non-decimal strings.
- Handle ValueError or TypeError with try/except when input might be invalid.
- Trim whitespace and remove thousands separators before conversion.
- For floats represented as strings, consider parsing float first then converting with int() if appropriate.
- Use str() or formatting to convert integers back to strings (python int to string).
Reference: Python's built-in int() and str() functions — consult the official docs for details on the int() base parameter and accepted input formats.