In Python, strings and numeric types like integers, floats, and complex numbers are fundamental data types that are used extensively in code. A core skill in Python programming involves converting between string representations of data and numeric types. This allows you to take inputs as strings, manipulate and process the values numerically, and then output the final results back as strings.
This guide will provide a comprehensive overview of techniques for converting between strings and numeric data types in Python. We will cover:
Table of Contents
Open Table of Contents
Converting Strings to Integers and Floats
In Python, the int()
and float()
built-in functions can be used to convert string representations of whole numbers and decimal numbers to numeric types.
String to Integer
To convert a string to an integer, pass the string into int()
:
num_str = "456"
num_int = int(num_str)
print(num_int)
# 456
print(type(num_int))
# <class 'int'>
int()
can convert strings containing digits 0
to 9
and an optional -
sign to negatives. Leading and trailing whitespace is ignored.
int(" -300") # -300
int("700") # 700
String to Float
To convert strings to floating point numbers, use float()
:
num_str = "123.45"
num_float = float(num_str)
print(num_float)
# 123.45
print(type(num_float))
# <class 'float'>
float()
supports decimal points, exponents, and optionally a -
sign. Like int()
, whitespace is ignored.
float(" -15.5") # -15.5
float("3.14159") # 3.14159
float("2.5e3") # 2500.0
Invalid Literal Errors
If a string cannot be converted to an integer or float, a ValueError
exception is raised:
int("123.5")
# ValueError: invalid literal for int()
float("text")
# ValueError: could not convert string to float: 'text'
To handle these errors, you can wrap the conversion in a try/except
block:
try:
num = float(input("Enter a number: "))
except ValueError:
print("Invalid number entered")
This catches the conversion error and prints a custom error message instead of crashing.
Converting Numeric Types to Strings
In Python, the str()
built-in can convert integers, floats, and other numeric types to string form. This allows you to output and serialize numeric data.
Integer to String
Pass an integer into str()
to convert to a string:
num = 456
num_str = str(num)
print(num_str)
# '456'
print(type(num_str))
# <class 'str'>
Float to String
Floats are converted analogously:
val = 123.456
val_str = str(val)
print(val_str)
# '123.456'
print(type(val_str))
# <class 'str'>
By default, str()
converts floats to a decimal representation with 6 digits of precision. We can control the precision using formatting covered later.
Complex Numbers and Other Types
str()
can handle other numeric types like complex numbers and decimals:
from decimal import Decimal
complex_num = 1 + 2j
complex_str = str(complex_num)
# '(1+2j)'
decimal_num = Decimal("0.5")
decimal_str = str(decimal_num)
# '0.5'
This allows converting any numeric type to a human-readable string form.
Formatting Stringified Numbers
By default, str()
converts floats to a truncated decimal representation and integers to their string numeral form. To control the formatting of stringified numbers, we can use formatting mini-languages like:
- f-strings
- str.format()
- % operator
f-strings
f-strings allow embedding expressions directly inside string literals prefixed with f
:
num = 123.456789
f"{num}" # default str() conversion
# '123.456789'
f"{num:.2f}" # round to 2 decimal places
# '123.46'
f"{num:e}" # exponent notation
# '1.234568e+02'
f-strings provide convenient inline number formatting.
str.format()
The str.format() method allows numbering placeholders {}
to substitute formatted values:
"The number is {:.3f}".format(123.456)
# 'The number is 123.456'
"The hex number is {:x}".format(456)
# 'The hex number is 1c8'
"The exponents is {:e}".format(3000)
# 'The exponents is 3.000000e+03'
This provides full control over string formatting.
%-formatting
The %
operator also allows embedding format specifiers like %f
, %x
, and %e
:
"Number: %f" % 123.456
# 'Number: 123.456000'
"Hex: %x" % 456
# 'Hex: 1c8'
"Exponents: %e" % 2500
# 'Exponents: 2.500000e+03'
Overall, use f-strings or str.format() for most formatting needs, and %
formatting when support for older Python versions is needed.
Best Practices
Here are some best practices when converting between strings and numbers in Python:
-
Use
try/except
blocks to catch conversion errors and make your program resilient. -
Leverage f-strings or str.format() for inline string formatting of numbers for clearer code.
-
When processing multiple data types, use conditionals to check types before converting to prevent errors.
-
For inputs, convert to numbers as early as possible to cache numeric values instead of repeatedly converting.
-
Avoid using
float()
for currency or values where precision is important - usedecimal.Decimal
instead. -
Set precision and formatting on stringified floats to avoid confusing representation differences like
0.1
becoming0.100000001
. -
Use comments and docstrings to document any non-obvious type conversions.
By following these best practices, you can reliably handle conversions between strings and numbers in your Python code.
Conclusion
This guide covered various techniques for converting between string and numeric data types in Python:
-
int()
andfloat()
convert strings to integer and floating point numbers respectively. -
str()
converts integers, floats, and other types to human-readable string representations. -
Formatting mini-languages like f-strings provide control over precision and formatting of stringified numbers.
-
Exceptions during conversions can be handled with
try/except
blocks. -
Following best practices avoids pitfalls when processing different data types.
Converting between strings and numbers is essential in Python programming. This guide and its sample code snippets demonstrate the key tools and techniques for robust type handling. With practice, you will be able to effortlessly convert between representations and process data in your Python projects.