Converting Data Types in Python
Introduction
In Python, data types determines the type of a data.
It defines what values can be assigned to it and what operations can be performed on it.
While programming, sometimes in order to process data in different ways
We may need to do type conversion.
For example:
- We may want to concatenate a numerical value with text.
- Or a number initially defined as integer,
We may need to convert it to float type to display decimal values.
In this guide, we will learn the most practical ways to convert between data types in Python.
In this guide, numbers, strings, tuples
and you will learn step by step how to convert between lists.
Converting Number Types
There are two basic numeric data types in Python:
- Integers
- Decimal numbers (floating-point numbers / floats)
Sometimes, when you are working on code written by someone else, you may need to convert an integer (int) to a decimal number (float), or vice versa, it may be better to use int instead of float.
Fortunately, Python allows you to easily perform these conversions.
It has built-in functions.
Converting Integers to Float
In Python, the float() method is used to convert integers (int) to decimal numbers (float).
To do this, simply write the integer you want to convert in parentheses:
float(32)
In this example, the number 32 is converted to 32.0.
We can also do the same operation with a variable.
For example, we assign the value 32 to the variable f,
Then let's convert it with the float() function:
f = 32
print(float(f))
Output
32.0
Using the float() function, we can easily convert integers (int) to decimal numbers (float).
This is very useful when we want to obtain more precise results in numerical operations.
Converting Floats to Integers
Python also has a built-in function for converting decimal numbers (float) to integer (int): int().
This function works similarly to the float() function.
You can perform the operation by typing the decimal number you want to convert in parentheses:
int(324.9)
In this example, the number 324.9 is converted to 324.
We can also do the same with variables.
For example, let's assign the values 764.0 to variable b and 324.9 to variable c
and then let's convert them with the int() function:
b = 764.0
c = 324.9
print(int(b))
print(int(c))
Output
764
324
When we convert a float to an int using the int() function, Python cuts off the decimal part** of the number and takes only the whole part.
So, for example, when we convert the number 390.8, the result is 390.
Python does not do rounding during this process. It just discards the decimal part.
Number Conversion by Division
In Python 3, when a divide operation is performed, the result is automatically converted to float.
This is different from Python 2 — in Python 2 the result was usually returned as an integer.
a = 5 / 2
print(a)
Output
2.5
In Python 2, division between two integers (int) would return the result as an integer.
Converting with Strings
String is a sequence of one or more characters (letters, numbers, or symbols).
Strings are widely used in programming and are often
We need the string ↔ number conversion.
Especially since the data received from the user usually comes as string,
In order to process these values, sometimes converting them to numbers,
Sometimes it may be necessary to convert numerical data to string.
First, let's look at an example of converting an integer to a string.
To convert the number 35 to a string, we can send the value 35 to the str() method:
str(35)
When you open the Python interactive shell (python) in the terminal and run the command str(12),
The following output is printed on the screen:
Output
'35'
quotes around the number 12 indicate that this value is no longer an integer (int),
Indicates that it is a string (text).
When working with variables, we can see more clearly how practical it is to convert integers to strings.
Let's say we're tracking a user's daily coding progress and
We record in the system how many lines of code are written each time.
When giving feedback to the user, we may want to display both text (string) and number (int) values together:
kullanici = "Ahmet"
satir = 50
print("Tebrikler, " + kullanici + "! Az önce " + satir + " satır kod yazdın.")
When we run this code we get the following error:
TypeError: can only concatenate str (not "int") to str
We cannot directly combine string and integer values in Python.
So we need to convert variable satir to string before concatenating:
kullanici = "Ahmet"
satir = 50
print("Tebrikler, " + kullanici + "! Az önce " + str(satir) + " satır kod yazdın.")
Now when we run the code we get the following output congratulating the user:
Tebrikler, Ahmet! Az önce 50 satır kod yazdın.
If we want to convert a decimal number (float) to a string rather than an integer,
We still follow the same steps and format.
When we send a float value to the str() method, Python returns us the string equivalent of this value.
We can do this either directly with a number or via a variable:
print(str(98.76))
sayi = 1204.89
print(str(sayi))
Output
98.76
1204.89
To test that the conversion is done correctly, we can check the string value we obtained by combining it with another text:
sayi = 1204.89
print("Toplam tutar: " + str(sayi) + " TL")
Output
Toplam tutar: 1204.89 TL
Since the merging process is completed without error,
We can make sure that our decimal number (float) has been successfully converted to string.
Python now sees this value as text.
Converting Strings to Numbers
We can use int() and float() functions to convert String values to numbers.
If the string value does not contain decimals, we usually want to convert it to an integer using int().
For example, in a situation where we track the lines of code that user Ahmet writes every day, we may want to analyze these values with mathematical operations.
But currently these values are stored as string:
satir_dun = "50"
satir_bugun = "108"
satir_fark = satir_bugun - satir_dun
print(satir_fark)
Output
TypeError: unsupported operand type(s) for -: 'str' and 'str'
We got an error because the two numeric values were stored as string (text). The - (subtraction) operator is not valid between two strings.
To solve this error, we need to convert string values to integer (int).
We can do this easily using the int() function:
satir_dun = "50"
satir_bugun = "114"
satir_fark = int(satir_bugun) - int(satir_dun)
print(satir_fark)
Output
64
In this example, the variable satir_fark is automatically of type integer (int) as a result of the operation
and its value is 64.
If we want to get the result as decimal number (float),
Instead of int() we can use the function float():
Our user Ahmet now earns decimal values.
In this case, we need to work with the float type to calculate the points correctly.
toplam_puan = "5524.53"
yeni_puan = "45.30"
yeni_toplam = toplam_puan + yeni_puan
print(yeni_toplam)
Output
5524.5345.30
In this case, the + operator is a valid operation between two strings,
However, this operation does not mean collection, but concatenation.
So instead of performing numerical operations, Python just writes the values "5524.53" and "45.30" side by side.
toplam_puan = "5524.53"
yeni_puan = "45.30"
yeni_toplam = float(toplam_puan) + float(yeni_puan)
print(yeni_toplam)
5569.83
Now that we have converted the two string values to float type,
We got the result we expected: 5524.53 + 45.30 = 5569.83
Because Python now recognizes these values as decimal numbers
performed real mathematical addition.
If a string value containing decimals is entered directly with the function int()
If we try to convert to integer, Python throws an error:
sayi = "45.67"
print(int(sayi))
Output
ValueError: invalid literal for int() with base 10: '45.67'
If we have a decimal value in a string and pass it directly to the int() function,
Python cannot convert this value to an integer and gives an error.
Converting strings to numbers allows us to quickly change the type of data we have.
Thus, on numerical data that initially comes as text (string)
We can perform mathematical operations and carry out our calculations without any problems.
Converting to Tuple and List
Using list() and tuple() functions in Python,
You can convert the data to list (list) or tuple (tuple) data type respectively.
These functions take the value given to them and create a new collection according to the specified data structure.
-
A list (list), defined within square brackets [ ],
It is a mutable and ordered data group. -
If it is a tuple, it is defined within brackets ( )
and immutable is an ordered data group.
Converting to Tuple
Let's start by converting a list into a tuple.
Since tuple is an immutable data type,
This transformation can provide a more efficient (optimized) structure in our programs.
When we use the tuple() method,
Returns the tuple version of the value given in parentheses:
meyveler = ["elma", "muz", "kiraz"]
meyve_tuple = tuple(meyveler)
print(meyve_tuple)
('elma', 'muz', 'kiraz')
As you can see, the output is now a tuple;
elements are enclosed in regular brackets ( ) rather than square brackets [ ].
Now, let's use the tuple() method on a variable that represents a list:
sayilar = [1, 2, 3, 4]
sayilar_tuple = tuple(sayilar)
print(sayilar_tuple)
(1, 2, 3, 4)
As we see again, the list value turned into a tuple and this
It can be understood by the items being placed in brackets ( ).
And not just lists, but also any iterable data type.
It can be converted to a tuple with the tuple() function — this includes strings:
kelime = "Python"
harfler = tuple(kelime)
print(harfler)
('P', 'y', 't', 'h', 'o', 'n')
Since Strings are iterable,
They can easily be converted to tuple using the tuple() method.
However, for non-iterable data types such as integer (int) or decimal number (float)
If we try to do the same operation, Python returns a TypeError:
print(tuple(5000))
Output
TypeError: 'int' object is not iterable
Although it is possible to first convert the number to string and then to tuple as tuple(str(5000)),
such operations create unnecessary complexity.
In Python, the best practice is to write simple and readable code, so if the conversion is really needed, it is always better to do it in a clear and logical way.
Convert to List
In some cases, you may specifically want to convert tuple data into a list.
This is because lists are mutable —
So you can edit the content later.
To make this conversion we use the list() method.
Since parentheses are used in the list creation syntax,
Don't forget to add the parentheses of the list() method and the print() function:
print(list(('kırmızı', 'mavi', 'yeşil')))
['kırmızı', 'mavi', 'yeşil']
Square brackets [ ] indicate that the result returned from method list() is now a list.
So the original tuple value has been successfully converted to a list.
To improve the readability of the code, instead of directly writing the function list() into print()
First we can assign the result to a variable:
renkler = ("kırmızı", "mavi", "yeşil")
renk_listesi = list(renkler)
print(renk_listesi)
['kırmızı', 'mavi', 'yeşil']
Just like tuples, string values can be converted to a list with the list() method:
kelime = "Python"
harf_listesi = list(kelime)
print(harf_listesi)
['P', 'y', 't', 'h', 'o', 'n']
Here, the string 'shark' is converted to a list, resulting in a mutable version of the original value.
So now you can delete, add or change letters in the list one by one.
Result
In this Python guide, you'll learn how to convert important built-in data types into each other.
While doing this, we mostly used Python's built-in methods.
The ability to convert data types gives you more flexibility when writing programs.
In this way, by converting strings to numbers, lists to tuples, and vice versa
can process data in accordance with different situations,
You can develop more dynamic, robust and powerful Python applications.

