This article will show you how to use Python’s built-in variable conversion functions, with examples.
A variable’s type determines what kind of data it can store and what can be done with it.
For example, string typed variables contain sequences of characters that can be joined and split (think words and sentences). In contrast, numeric typed variables contain numeric values intended to be used in calculations.
Being able to convert a variable’s type allows data to be used in different ways.
Converting a Variable to a String
myNumber = 3 myString = str(myNumber) # myString will have a value of "3" - a string containing a numeric character
Converting a Variable to an Integer (Number)
Likewise, if a non-numeric variable contains a value that can be parsed as a number, the int() function will return that number:
myString = "4" myNumber = int(myString) # myNumber will have the integer value of 4
If you supply a variable to int() which cannot be parsed as a number, an error will be thrown.
If a non-integer number is supplied, precision will be lost, and it will be converted to an integer.
Converting a Variable to a Float (Number)
Python supports both integer and floating-point numbers. Integer variables, as explained above, can only contain whole-number values. Floating point numbers can support higher precision – allowing for decimal places.
The float() function converts a given value or variable to its floating-point value if it can be parsed. If it cannot be parsed as a floating-point number value, an error will be thrown.
myString = "2.5" myNumber = float(myString) # myNumber will have the float value of 2.5
Integers can also be provided to the float() function and floats to the integer() function to convert between the two types.
Converting a Variable to a List
The list() function will convert a given variable to a list. Strings and iterables can be converted to lists – this is used when converting lists to strings and back (see further down for more on this).
myString = "abcd" myList = list(myString) # myList will have the list value ['a', 'b', 'c', 'd']
Again, if the given value can’t be parsed to a list, an error will be thrown.
Converting a Variable to a Tuple
As explained in the above article, a tuple is similar to a list but unchanging and ordered. The tuple() function will convert a variable to a tuple if it can be parsed as such:
myString = "abcd" myTuple = list(myString) # myList will have the tuple value ['a', 'b', 'c', 'd']
Converting a List to String / String to List
Converting lists to strings and strings to lists requires a bit of extra work as there are no built-in functions for it – check out our article on how to do it here.