Introduction
Python allows you to convert strings, integers, and floats interchangeably in a few different ways. The simplest way to do this is using the basic str()
, int()
, and float()
functions. On top of this, there are a couple of other ways as well.
Before we get in to converting strings to numbers, and converting numbers to strings, let's first see a bit about how strings and numbers are represented in Python.
Note: For simplicity of running and showing these examples we'll be using the Python interpreter.
Strings
String literals in Python are declared by surrounding a character with double (") or single quotation (') marks. Strings in Python are really just arrays with a Unicode for each character as an element in the array, allowing you to use indices to access a single character from the string.
For example, we can access individual characters of these strings by specifying an index:
>>> stringFirst = "Hello World!"
>>> stringSecond = 'Again!'
>>> stringFirst[3]
'l'
>>> stringSecond[3]
'i'
Numerics
A numeric in Python can be an integer
, a float
, or a complex
.
Integers can be a positive or negative whole number. Since Python 3, integers are unbounded and can practically hold any number. Before Python 3, the top boundary was 231-1 for 32-bit runtimes and 263-1 for 64-bit runtimes.
Floats have unlimited length as well, but a floating-point number must contain a decimal point.
Complex numerics must have an imaginary part, which is denoted using j
:
>>> integerFirst = 23
>>> floatFirst = 23.23
>>> complextFirst = 1 + 23j
Converting Strings to Numerics
Using the int() Function
If you want to convert a string to an integer, the simplest way would be to use int()
function. Just pass the string as an argument:
>>> x = "23"
>>> y = "20"
>>> z = int(x) - int(y)
>>> z
3
This works as expected when you're passing a string-representation of an integer to int()
, but you'll run in to trouble if the string you pass doesn't contain an integer value. If there are any non-numeric characters in your string then int()
will raise an exception:
>>> x = "23a"
>>> z = int(x)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '23a'
This same exception will even be raised if a valid float string is passed:
>>> x = "23.4"
>>> z = int(x)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '23.4'
The int()
function does have another useful feature than just converting strings to integers, it also allows you to convert numbers from any base to a base 10 integer. For example, we can convert the following binary string to a base 10 integer using the base
parameter:
>>> int('1101100', base=2)
108
The same can be done for any other base, like hexadecimal (base 16):
>>> int('6C', base=16)
108
Using the float() Function
Converting string literals to floats is done via the float()
function:
>>> x = "23.23"
>>> y = "23.00"
>>> z = float(x) - float(y)
>>> z
0.23000000000000043
Notice that the resulting value is not entirely accurate, as it should just be 0.23
. This has to do with floating point math issues rather than the conversion from string to number.
The float()
function offers a bit more flexibility than the int()
function since it can parse and convert both floats and integers:
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
>>> x = "23"
>>> y = "20"
>>> z = float(x) - float(y)
>>> z
3.0
Unlike int()
, float()
doesn't raise an exception when it receives a non-float numeric value.
However, it will raise an exception if a non-numeric value is passed to it:
>>> x = "23a"
>>> z = float(x)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: '23a'
While float()
does not have the ability to convert non-base 10 numbers like int()
does, it does have the ability to convert numbers represented in scientific notation (aka e-notation):
>>> float('23e-5')
0.00023
>>> float('23e2')
2300.0
Using the complex() Function
Converting string literals to complex numerics is done via the complex()
function. To do so, the string must follow specific formatting. Particularly, it must be formatted without white spaces around the +
or -
operators:
>>> x = "5+3j"
>>> y = "3+1j"
>>> z = complex(x) + complex(y)
>>> z
(8+4j)
Having any extra spaces between the +
or -
operators will result in a raised exception:
>>> z = complex("5+ 3j")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: complex() arg is a malformed string
Like the float()
function, complex()
is also more relaxed in the types of numbers it allows. For example, the imaginary part of the number can be completely omitted, and both integers and floats can be parsed as well:
>>> complex("1")
(1+0j)
>>> complex("1.2")
(1.2+0j)
As you can see, however, this should not be used as a more flexible replacement for int
/float
since it automatically adds the imaginary part of the number to the stringified version.
Converting Numerics to Strings
Using the str() Function
The str()
function can be used to change any numeric type to a string.
The function str()
is available from Python 3.0+ since the strings in Python 3.0+ are Unicode by default. However, this is not true for Python versions below 3.0 - in which to achieve the same goal, the unicode()
function is used:
>>> str(23) # Integer to String
'23'
>>> str(23.3) # Float to String
'23.3'
>>> str(5+4j) # Complex to String
'(5+4j)'
The nice thing about str()
is that it can handle converting any type of number to a string, so you don't need to worry about choosing the correct method based on what type of number you're converting.
Using the format() Function
Another way of converting numerics to strings is using the format()
function, which allows you to set placeholders within a string and then convert another data type to a string and fill the placeholders.
To use the function, simply write a string followed by .format()
and pass the arguments for the placeholders.
Here's an example:
>>> "My age is {}".format(21)
'My age is 21'
The arguments in the .format()
function can also be referred to individually, using their positions or variable names:
>>> "You get {product} when you multiply {1} with {0}".format(5.5, 3, product=16.5)
'You get 16.5 when you multiply 3 with 5.5'
Note that underneath the hood, the .format()
function simply uses str()
to convert the arguments to strings. So essentially this is a similar way of converting numbers to strings as the previous section, but .format()
acts as a convenience function for formatting a string.
Conclusion
Python allows you to convert strings, integers, and floats interchangeably in a few different ways. The simplest way to do this is using the basic str()
, int()
, and float()
functions. On top of this, there are a couple of other ways as well such as the format()
function. Just keep in mind that the int()
, float()
, and complex()
functions have their limitations and may raise exceptions if the input string isn't formatted exactly as they expect.