Python string is a sequence of characters, and an integer is a numeric value. You cannot perform arithmetic operations on a string, for that, you must convert that string representation to a numeric value.
For example, if you use the input() function to get the input from a user, its value is always a string. To perform summation, you must convert that string value to an integer value.
The easiest and most efficient way to convert a string to an integer in Python is to use the “int()” function. It accepts a valid string integer literal as an argument and returns an integer. For example, int(“456”) would return 456.
Basic conversion
Define a valid string that is an integer literal:
string_value = "1921" print(string_value) # Output: "1921" print(type(string_value)) # Output: <class 'str'> integer_value = int(string_value) print(integer_value) # Output: 1921 print(type(integer_value)) # Output: <class 'int'>
You can also use the string.isdigit() method before conversion to check whether all characters in a string are digits. If all characters are digits, the method returns True. After that, you can use the int() function for the conversion.
def convert_to_integer(value: str): """Converts a string to an integer if it represents a valid number.""" if value.isdigit(): integer_value = int(value) print(f"Converted Value: {integer_value}") print(f"Type: {type(integer_value)}") else: print(f"Error: '{value}' is not a valid integer.") # Example usage string_value = "101" convert_to_integer(string_value) # Output: # Converted Value: 101 # Type: <class 'int'>
Handling Signs
In practical applications, the string contains positive (+) or negative (-) sign. During conversion, those signs are handled automatically. It won’t throw any errors.
string_value = "-1921" print(string_value) # Output: "-1921" print(type(string_value)) # Output: <class 'str'> integer_value = int(string_value) print(integer_value) # Output: -1921 print(type(integer_value)) # Output: <class 'int'>
Whitespace
If a valid integer string contains whitespace, the int() function ignores it and returns the normal integer output.
str_int = " 45 " num = int(str_int) print(num) # Output: 45 print(type(num)) # Output: <class 'int'>
Empty Strings
Your input string maybe empty. So, check before conversion.
str = "" if str.strip(): num = int(str)
Leading Zeros
If your string contains 0s at the start of the string, you can strip it using the lstrip() function.
data_str = "00123" print(data_str) # Output: 00123 print(type(data_str)) # Output: <class 'str'> main_str = data_str.lstrip("0") num = int(main_str) print(num) # Output: 123 print(type(num)) # Output: <class 'int'>
Specifying a Base (Binary, Octal, Hexadecimal)
What if a string is in a different base? The int() function accepts the “base” as a second argument. So, you can use the “base” argument to convert that string into an appropriate integer. Like hexadecimal or binary. Just make sure that the string is appropriate for the given base.
For example, int(“1a”, 16) would convert the hexadecimal “1a” to 26 in decimal.
Binary string
num = int("1010", 2) print(num) # Output: 10 print(type(num)) # Output: <class 'int'>
Octal string
num = int("12", 8) print(num) # Output: 10 print(type(num)) # Output: <class 'int'>
Hex string
num = int("A", 16) print(num) # Output: 10 print(type(num)) # Output: <class 'int'>
Auto-Detect Base
Use base=0 to infer from prefixes (0b, 0o, 0x):
num = int("0b1010", 0) print(num) # Output: 10 print(type(num)) # Output: <class 'int'> num_2 = int("0x1A", 0) print(num_2) # Output: 26 print(type(num_2)) # Output: <class 'int'>
Preprocessing Strings
Remove Commas/Currency Symbols
If a string contains a valid integer but also has symbols or commas, we can replace it with an empty string using the replace() method and then convert the string into an integer.
price = "$1,234" print(price) # Output: $1,234 print(type(price)) # Output: <class 'str'> num = int(price.replace("$", "").replace(",", "")) print(num) # Output: 1234 print(type(num)) # Output: <class 'int'>
Scientific Notation
If your input string contains scientific letters like “e“, you can use the float() function to normalize the value and then apply the int() function to it.
data_str = "1.23e4" print(data_str) # Output: 1.23e4 print(type(data_str)) # Output: <class 'str'> num = int(float(data_str)) print(num) # Output: 12300 print(type(num)) # Output: <class 'int'>
Locale-Specific Parsing
Python provides a “locale” module that you can use to set the locale for your current program and then convert it.
import locale locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') data_str = "5,678" print(data_str) # Output: 1.23e4 print(type(data_str)) # Output: <class 'str'> num = int(locale.atoi(data_str)) print(num) # Output: 5678 print(type(num)) # Output: <class 'int'>
Converting from Float Strings
If you are dealing with a string representing floating-point numbers, you can truncate decimal values or round them before converting them into an integer.
Truncate Decimal Values
float_str = "123.45" print(float_str) # Output: 123.45 print(type(float_str)) # Output: <class 'str'> num = int(float(float_str)) print(num) # Output: 123.45 print(type(num)) # Output: <class 'int'>
Rounding First
float_str = "123.6" print(float_str) # Output: 123.6 print(type(float_str)) # Output: <class 'str'> num = int(round(float("123.6"))) print(num) # Output: 124 print(type(num)) # Output: <class 'int'>
Here are two alternate ways to convert a string to an integer for your knowledge:
Alternate approach 1: Using ast.literal_eval()
The ast.literal_eval() function accepts a string and returns an integer. It is helpful when you parse the data from untrusted sources or when you need to ensure that only safe literals are evaluated from a string.
from ast import literal_eval string_value = "101" print(string_value) # Output: "101" print(type(string_value)) # Output: <class 'str'> integer_value = literal_eval(string_value) print(integer_value) # Output: 101 print(type(integer_value)) # Output: <class 'int'>
Alternate approach 2: Using eval()
The eval() method is not recommended due to security risks security risk if the input is not sanitized because it can execute arbitrary code. It accepts a string as an argument and returns an integer representation.
string_value = "101" print(string_value) # Output: "101" print(type(string_value)) # Output: <class 'str'> integer_value = eval(string_value) print(integer_value) # Output: 101 print(type(integer_value)) # Output: <class 'int'>
That’s all!
Hiral
Thanks for posting, this article was very helpful when converting string to int and vice versa. I came across a similar post though it was certainly not quite as thorough as this!
Thanks again,
uptoword
This is a great tutorial on how to convert a string to an integer in Python.