- Convert Strings to Numbers and Numbers to Strings in Python
- Strings
- Numerics
- Converting Strings to Numerics
- Using the int() Function
- Using the float() Function
- Free eBook: Git Essentials
- Using the complex() Function
- Converting Numerics to Strings
- Using the str() Function
- Using the format() Function
- Conclusion
- Python complex() Function
- Syntax
- Creating Complex Numbers
- Convert a String to a Complex Number
Convert Strings to Numbers and Numbers to Strings in Python
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 2 31 -1 for 32-bit runtimes and 2 63 -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 "", line 1, in 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 "", line 1, in 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:
The same can be done for any other base, like hexadecimal (base 16):
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:
Free eBook: Git Essentials
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 "", line 1, in 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 "", line 1, in 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.
>>> "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 when you multiply with ".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.
Python complex() Function
The complex() function creates a complex number when real and imaginary parts are specified.
It can also convert a string to a complex number.
The complex number is returned in the form of real + imaginary , where the imaginary part is followed by a j.
Syntax
Parameter | Condition | Description |
real | Optional | The real part of the complex number. Default is 0. |
imaginary | Optional | The imaginary part of the complex number. Default is 0. |
Creating Complex Numbers
You can create a complex number by specifying real and imaginary parts.
x = complex(3, 2) print(x) # Prints (3+2j) x = complex(-3, 2) print(x) # Prints (-3+2j) x = complex(3, -2) print(x) # Prints (3-2j)
If you omit one of the arguments, it is assumed as 0; because the default value of real and imaginary parameters is 0.
# omit imaginary part x = complex(3) print(x) # Prints (3+0j) # omit real part x = complex(0, 4) print(x) # Prints 4j # omit both x = complex() print(x) # Prints 0j
Convert a String to a Complex Number
You can convert a string to a complex number by specifying the first parameter as a string like ‘3+4j’ . In this case the second parameter should be omitted.
# Convert a string '3+4j' to a complex number x = complex('3+4j') print(x) # Prints (3+4j)
When converting from a string, the string must not contain whitespace around the central + or – operator. Otherwise, the function raises ValueError .
# Triggers ValueError: complex() arg is a malformed string x = complex('3 + 4j') print(x)