Every variable in Python has a Datatype. Although you don't declare them while using them declarations happen automatically when you assign a value to the variable.
These datatypes play an essential role in programming because they determine what kind of operation can be performed on the value. You can read more about Python Data types here
Often you need to change the datatype of the variable or the value to do a different datatype.
In this article, we will learn how to convert data types in Python with in-built methods.
Implicit and Explicit Data Type Conversion
Data type conversion in Python can take place in two ways, either you force Python to convert it to a specific datatype or Python itself does that during compilation.
When you force the compiler for conversion, it is called Explicit Data Type Conversion and when Python itself does the work, it's called implicit Data Type conversion.
A good example of implicit data type conversion can be seen by performing a simple division,
>>> a = 3 >>> b=2 >>> c = a/b >>> print(c)1.5
We did an operation on two integers and stored the result into another variable Python compiler itself converted the result to a float value to prevent Data loss, and this is a quite effective feature of Python.
Another example of implicit data type conversion can be,
>>> a= 3 >>> b = 3.0 >>> print(a+b) 6.0
In this example, we added an integer with a float, and the result automatically gets converted into a float.
All these Implicit conversions are the result of Python compiler defense mechanism which is firmly against data loss.
Now, let's have a look at Explicit conversions.
Converting Number Types
Python has three number types - integer, float and complex. Although you will mostly use Integer and float numbers in your program.
Python comes with inbuilt methods to convert an integer to float and float to an integer.
Converting Integers to Floats
float() method in Python converts integers to floats. We can simply pass the integer itself or a variable storing integer inside the parenthesis, Like this
>>> a = 8 >>> float(a)8.0
Converting Floats to Integers
Int() method is used to convert floats into integers,
>>> b = 6.9 >>> int(b) 6
However, you might have noticed Python doesn't return a round figure integer, it simply cuts off the decimal part.
Converting Numbers to Strings
A string in Python is a sequence of alphanumeric characters wrapped inside single or double quotes.
str() method is used to convert numbers either be integer or float to a string.
>>> str('39.8') '39.8'
Quotation marks around the number indicated that it is no longer a number.
A better real-world example would be:
>>> item_a = 20 >>> item_b = 30 >>> total = item_a + item_b >>> print("Your grand total is " + str(total) +" rupees.") Your grand total is 50 rupees.
We need to have the items in numbers to perform addition, but we must convert total to a string to concatenate with the final string object.
Converting Strings to Numbers
Strings can be converted into numbers by either
However, keep in mind that
int() method won't convert a string which has a decimal number in it, use
float() method in such condition.
>>> float("345.76") 345.76
Till now we were converting primitive datatypes which are the basic building blocks of any data structure now let's learn how to convert non-primitive data structures like lists and tuple.
Conversion of Non Primitive datatypes
List and tuple both are used to group data of similar or different data types.
Tuples are ordered sequence of items contained within parenthesis(). Tuples are immutable, which means the items of tuples cannot be updated or deleted.
Similar to tuples, Lists are ordered sequence of items contained in , but they are mutable which mean they can be updated, deleted or a new item can be inserted into the existing list.
Converting Lists into Tuple
Tuples are immutable, converting lists into tuple can provide a significant performance boost to the existing program, you can do this by Python's
>>> my_list = ["item1", "item2", 234.86] >>> tuple(my_list) ('item1', 'item2', 234.86)
The parenthesis() indicates that it is no longer a list.
Converting Tuples into Lists
Lists are mutable, converting lists into tuple gave you the ability to add, delete and update elements.
list() method is used to convert tuples into list.
>>> my_tuple = ("item1", "item2", 234.86) >>> list(my_tuple) ['item1', 'item2', 234.86]
The square brackets indicate that the operation returns a list.
Convert String into tuples and Lists
A string can be converted into List and Tuple through their respective conversion method.
>>> tuple("String") ('S', 't', 'r', 'i', 'n', 'g') >>> list("String") ['S', 't', 'r', 'i', 'n', 'g']
Notice the brackets they confirm that the conversion was successful.