While Python handles data types automatically, sometimes the program may require us to use exact specific data types rather than relying on the language to figure out what data types would be appropriate. Data types in Python allow you to classify data, define the values that can be assigned, and the operations that can be performed on that data. In programming, it may be necessary to convert one data type to another in order to gain access to other functions, such as gluing numeric values to strings, or representing integers as decimals.
This tutorial teaches you how to convert numbers, strings, tuples, and lists.
Converting numeric types
There are two numeric data types in Python: integers and floating point numbers. Python provides special built-in methods for converting integers to floating point numbers and vice versa.
Converting integers to floating point numbers
The float () method converts integers to floating point numbers. The number is indicated in parentheses:
This converts the number 45 to 45.0. We can also use variables. Declare the variable f = 45 and then print the floating point number:
f = 45 print(float(f))
Converting floating point numbers to integers
The int() built-in function converts floating point numbers to integers. The int () function works the same as float (). To convert a number, add it within parentheses:
The number 491.6 converts to 491. This function can also work with variables. Declare variables:
b = 129.0 c = 491.6
To get an integer, the int () function discards the decimal places without rounding them (because 491.6 is not converted to 492). You can also say that int() converts floating point number to the nearest small integer number.
A string is a sequence of one or more characters (numbers, letters, and other symbols). Strings are a very common data type in programming. There are many ways to convert strings.
Converting numbers to strings
To convert a number to a string, use the str() method. Place a number or variable in parentheses. Try converting an integer like:
By running the str (22) method in an interactive Python shell, you get the output:
The quotes indicate that the 22 value entered is now a string, not a number.
Many times we use to convert numbers to strings using variables.
For example, you have to track how many lines of code a user writes per day. If the user writes more than 100 lines, the program will send him a promotional message.
username = "Dave" linesofcode = 100 print("Congrats, " + username + "! You have written " + linesofcode + " lines of code.")
Running this code we get an error output relating to the improper use of datatypes within the program.
Output: Traceback (most recent call last): File "main.py", line 3, in print("Congrats, " + username + "! You have written " + linesofcode + " lines of code.") TypeError: can only concatenate str (not "int") to str
Python cannot concatenate strings with numbers, so you need to convert the value of lines to a string.
username = "Dave" linesofcode = 100 print("Congrats, " + username + "! You have written " + str(linesofcode) + " lines of code.")
Output: Congrats, Dave! You have written 100 lines of code.
The str() method can also convert float to string. Place a number or variable in parentheses:
print(str(447.074)) f = 6724.03 print(str(f))
Output: 447.074 6724.03
Try concatenating a string and a string-converted number:
f = 6724.03 print("Dave has " + str(f) + " points.")
Output: Dave has 6724.03 points.
Converting strings to numbers
Strings can be converted to numbers using the int() and float() methods. If the string does not contain decimal places, it is better to convert it to an integer using int() method.
a = "5524.53" b = "45.30" c = float(a) + float(b) print(c)
Converting to Tuples and Lists
To convert data to a tuple or list, we use the tuple () and list () methods, respectively. In Python: A list is a mutable, ordered sequence of elements, enclosed in square brackets . A tuple is an immutable, ordered sequence of elements, enclosed in parentheses( ). You can read about them in our list and tuple in python article.
Converting a list to a tuple
By converting the list to a tuple, you can optimize your program. The tuple () method is used to convert to a tuple.
a = ['apples', 'oranges', 'bananas ', 'grapes'] #defined a list called a print(tuple(a)) #converting the list into tuple and printing
Output: ('apples', 'oranges', 'bananas ', 'grapes')
The displayed data is a tuple, not a list, since it is enclosed in parentheses. Any iterable type can be converted to a tuple, including strings:
Output: ('E', 'l', 'i', 'z', 'a', 'b', 'e', 't', 'h')
Converting tuples to lists
You can convert a tuple to a list to make it mutable according to program requirements using list() method.
a = ('blue', 'red', 'purple') print(list(a))
If the data returned by the print method is enclosed in square brackets, then the tuple has been converted to a list.
Converting Strings to Lists
It works similar to converting tuple to a list.
Output: ['R', 'o', 's', 'e', 'a', 'n', 'n', 'e']
Now you can convert various Python data types using built-in methods, which can serve to make your code more flexible.