English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Using Python, we can easily convert data into different types. Type conversion has different functions. We can convert string objects to numbers, perform conversions between different container types, and so on.
In this section, we will see how to perform conversions using Python.
To convert a String object to a Numeric object, you can useint()
,float()
and other different methods. Using theint()
The method, we can convert any number to a string (in10as the base). It uses a string type parameter, with the default base as10, we can also specify the base to convert from a string of that base to a decimal number.
Similarly, using thefloat()
The method can convert a string containing a value in decimal form to float.
str_number = '56' print(int(str_number)) # default base is 10 print(int(str_number, 16)) # From Hexadecimal print(int(str_number, 12)) # From a number where base is 12 str_number = '25.897' print(float(str_number)) # convert string to floating point value
Output result
56 86 66 25.897
As is well known, a string is a collection of characters. But in Python, we cannot directly obtain the ASCII value of a character. We need to use theord()
The method converts a character to its ASCII value.
There are also other methods, such ashex()
,ord()
,bin()
Convert decimal numbers to hexadecimal, octal, and binary respectively numbered.
print('ASCII value of "G" is: ') + str(ord('G'))) print('Hexadecimal value of 254 is: ' + str(hex(254)) print('Octal value of 62 is: ' + str(oct(62)) print('Binary value of') 56 is: ' + str(bin(56))
Output result
ASCII value of "G" is: 71 Hexadecimal value of 254 is: 0xfe Octal value of 62 is: 0o76 Binary value of 56 is: 0b111000
In Python, there are different container type objects like lists, tuples, and sets. We can change one type of container to another by changing the container type.list()
,tuple()
,set()
etc.
my_list = [10, 20, 30, 40, 50] my_set = {10, 10, 20, 30, 20, 50, 20} print('From list to tuple: ' + str(tuple(my_list))) print('From list to set: ' + str(set(my_list))) print('From set to list: ' + str(list(my_set)))
Output result
From list to tuple: (10, 20, 30, 40, 50) From list to set: {40, 10, 50, 20, 30} From set to list: [10, 20, 50, 30]
In Python, there is a complex class. Therefore, using this method, we can convert two integers (real part and imaginary part) to a complex number.
my_complex = complex(10, 5) #convert to complex number print(my_complex)
Output result
(10+5j)
Tuples are one of the most important container types in Python. Using tuples, we can store some ordered data. In Python, we can convert a Tuple type object with two values to a dictionary object. Thedict()
The method can be used for conversion.
my_tuples = (('Tiger', 4), ('Cat', 6), ('Dog', 8), ('Elephant', 10)) my_dict = dict(my_tuples) print(my_dict)
Output result
{'Tiger': 4, 'Elephant': 10, 'Dog': 8, 'Cat': 6{}