Converting a string to a number in Python can be easily achieved using built-in functions int()
and float()
. Understanding how to do these conversions is essential in many programming scenarios, especially when dealing with user input or data parsing, where the values might initially be in string format but need to be used for numerical operations.
Let’s explore in detail how to convert strings to integers (int) and floating-point numbers (float).
Converting Strings to Integers – int()
To convert a string to an integer, you can use the built-in int()
function. This function takes a string as input and returns an integer. However, the string must represent a valid integer value; otherwise, Python will raise a ValueError
.
Syntax
int(value,base=10)
Parameters
The int()
function can take up to two arguments:
Parameter | Condition | Description |
value | Optional | The value you want to convert to an integer. This can be a string, a float, or any object that can be interpreted as a number. If value is not provided, int() returns 0. |
base | Optional | Specifies the base of the number. This parameter is only used when the value is a string. The valid range is between 2 and 36, inclusive. The default value is 10 (decimal). |
Examples
Let’s start with a basic example of how to use Python’s int()
function to convert strings to integers:
print(int("10")) # Output: 10
print(type(int("10"))) # Output: <class 'int'>
The int()
function can also handle strings with leading ‘+’ or ‘-‘ signs, representing positive or negative numbers, respectively.
print(int("+10")) # Output: 10
print(int("-10")) # Output: -10
It’s important to remember that the string you want to convert must contain only valid numerical characters. Attempting to convert a string with letters or other symbols will result in a ValueError
.
print(int("abc")) # ValueError: invalid literal for int() with base 10: 'abc'
Similarly, strings containing commas (for example, used as thousands separators) will also cause an error. To handle these, you need to preprocess the string by replacing the commas with an empty string (”) using the replace()
method.
print(int('1,000')) # ValueError: invalid literal for int() with base 10: '1,000'
print(int('1,000'.replace(',', ''))) # Output: 1000
Note that int()
cannot directly convert a string containing a decimal point into an integer. In such a case, you must first convert it to a float with float()
, and then to an integer.
int("10.99") # ValueError, since it's a string representing a float
int(float("10.99")) # Returns 10
Base Conversion
The int()
function also allows you to convert strings in different numerical bases to an integer.
By default, int()
assumes the string is in base 10 (decimal). However, you can specify a different base by providing a second argument to int()
. For example, to convert a binary, hexadecimal or octal string to an integer:
# Binary to decimal
print(int("10101010", 2)) # Output: 170
# Hexadecimal to decimal
print(int("AA", 16)) # Output: 170
# Octal to decimal
print(int("252", 8)) # Output: 170
Setting the base to 0 allows the string’s prefix (0b, 0o, 0x, 0B, 0O, 0X) to determine the conversion.
# Binary to decimal
print(int("0b10101010", 0)) # Output: 170
# Hexadecimal to decimal
print(int("0xAA", 0)) # Output: 170
# Octal to decimal
print(int("0o252", 0)) # Output: 170
Handling Errors
When a string doesn’t represent a valid integer, the int()
function will raise a ValueError
. This is a common scenario when dealing with user input, as users might enter unexpected values. To handle this gracefully, it’s recommended to use try-except blocks.
my_string = "not a number"
try:
my_int = int(my_string)
except ValueError:
print("This string cannot be converted to an integer.")
Converting Strings to Floating-Point Numbers – float()
To convert a string to a floating-point number, you use the built-in float()
function. However, the string must represent a valid floating-point number; otherwise, a ValueError
will occur.
Syntax
float(value)
Parameters
The float()
function can take a single argument:
Parameter | Condition | Description |
value | Optional | The value you want to convert to a floating-point number. This can be a string, an integer, another floating-point number, or special strings like ‘inf’, ‘-inf’, ‘Infinity’, ‘-Infinity’, ‘nan’, ‘NaN’. If value is not provided, float() returns 0.0. |
Examples
Here’s a basic example:
print(float("10.5")) # Output: 10.5
print(type(float("10.5"))) # Output: <class 'float'>
The float()
function can handle strings containing only a fractional part (e.g., “.42”) and even strings representing whole numbers:
print(float('.42')) # Output: 0.42
print(float('10')) # Output: 10.0
The float()
function works even if the string includes a leading ‘+’ or ‘-‘ sign, indicating positive or negative numbers respectively.
print(float("+10.5")) # Output: 10.5
print(float("-10.5")) # Output: -10.5
Additionally, float()
can handle strings representing numbers in scientific notation (using “e” or “E”).
print(float('1.23e-4')) # Output: 0.000123
print(float('1.23e4')) # Output: 12300.0
print(float('1.23E-4')) # Output: 0.000123
Just like with int()
, it’s important that the string you’re converting represents a valid numerical value. Attempting to convert a string with non-numeric characters will raise a ValueError
.
print(float("abc")) # ValueError: could not convert string to float: 'abc'
Handling Errors
When the string you’re trying to convert doesn’t represent a valid number, both the int()
and float()
functions will raise a ValueError
. It’s important to handle these cases, especially when dealing with user input. A reliable way to do this is using try-except blocks.
my_string = "not a number"
try:
my_float = float(my_string)
except ValueError:
print("This string cannot be converted to a float.")
Precision and Representation
It’s important to remember that floating-point numbers in Python, like in most programming languages, are internally represented using binary fractions. This representation can sometimes lead to unexpected results. For example:
print(float("0.1") + float("0.2")) # Output: 0.30000000000000004
The output might surprise you! Instead of the expected 0.3, you might see a slightly different value. This is due to the way computers handle the conversion between decimal and binary fractions.
Special Values
The float()
function has the capability of handling special string representations for “infinity” and “NaN” (Not a Number). These concepts are important in certain mathematical and computational contexts. Let’s see some examples:
print(float("inf")) # Positive infinity
print(float("-inf")) # Negative infinity
print(float("Infinity")) # Also works (case-insensitive)
print(float("nan")) # Not a Number
print(float("NAN")) # Also works (case-insensitive)
Using eval() for Number Conversion
The eval()
function actually evaluates a string as a Python expression and returns the result of the evaluated expression. This means that if you pass a string representing a number (integer or floating-point), eval()
will execute it and return the corresponding numerical value.
# Converting to integers
print(eval("10")) # Output: 10
print(type(eval("10"))) # Output: <class 'int'>
# Converting to floating-point numbers
print(eval("10.5")) # Output: 10.5
print(type(eval("10.5"))) # Output: <class 'float'>
Similar to int()
and float()
, eval()
also handles other numerical representations:
print(eval("+10")) # Output: 10 (positive sign)
print(eval("-10")) # Output: -10 (negative sign)
print(eval(".42")) # Output: 0.42 (only fractional part)
print(eval("1.23e-4")) # Output: 0.000123 (scientific notation)
Why is eval() Generally Not Recommended?
While eval()
can interpret and convert numeric strings to their corresponding numeric types, its use is generally discouraged. Here’s why:
- Security Risk: If the string you’re evaluating comes from an untrusted source like user input, using
eval()
poses a significant security vulnerability. A malicious user could inject arbitrary Python code within the string, potentially causing serious harm to your system. - Performance:
eval()
is generally slower thanint()
andfloat()
because it has to parse, compile, and then execute the expression.
So It’s strongly recommended to use the dedicated conversion functions int()
and float()
for converting strings to numbers. These functions are designed specifically for this task, making them safer and more efficient.
Integer string conversion length limitation
In Python versions released after September 7th, 2022 (specifically, 3.11, 3.10.7, 3.9.14, 3.8.14, 3.7.14, and later), a default limit of 4300 digits was introduced for converting strings to integers using the int()
function. Please refer to the official documentation.
Attempting to convert a string of integers longer than this limit will result in a ValueError
with the message: “Exceeds the limit (4300) for integer string conversion”.
number = int("1" * 4300) # works perfectly
number = int("1" * 4301)
# ValueError: Exceeds the limit (4300 digits) for integer string conversion: value has 4301 digits;
# use sys.set_int_max_str_digits() to increase the limit
This also applies to internal string conversions in functions like print()
and repr()
.
number = 10**10000
print(number)
# ValueError: Exceeds the limit (4300 digits) for integer string conversion: value has 4301 digits;
# use sys.set_int_max_str_digits() to increase the limit
Why Does This Limitation Exist?
The primary reason for this limitation is to prevent potential Denial-of-Service (DoS) attacks. Converting extremely large integers from strings has a time complexity of O(n²), where ‘n’ is the number of digits. A malicious actor could exploit this to overwhelm a system’s resources by intentionally providing oversized numbers.
Workarounds
If you legitimately need to work with integers exceeding this limitation, here are a few options:
- Arbitrary-Precision Arithmetic Library: Use a library like Python’s built-in decimal module, which is designed for handling numbers with arbitrary precision.
import decimal huge_number_string = "1" * 4301 huge_number = decimal.Decimal(huge_number_string) print(huge_number)
- Base Conversions: This limitation only applies to decimal (base 10) integer conversions via
int()
. Converting a string representing a number in a power-of-two base (like binary-2, octal-8, or hexadecimal-16) has no length limitations.huge_binary_string = "1" * 4301 huge_number = int(huge_binary_string, 2) print(huge_number)
- Overriding the default limit: The
sys.set_int_max_str_digits()
function can be used to override the default limit (but only for the current Python session). You provide a new desired limit as an argument to the function:import sys sys.set_int_max_str_digits(10000) # Allow strings up to 10000 digits
Passing 0 to the function effectively disables the length restriction. This means you can attempt to convert strings of any length.
sys.set_int_max_str_digits(0) # Disables the length restriction
However, use with extreme caution! Removing this limit can make your code vulnerable to security risks mentioned earlier.