Python Data Type Conversion

Python provides an easy way to convert in between different data types. During the program, we may need to perform some conversion among data types. Python provides several built-in functions to accomplish this task.

Loading…

What are different ways of converting data types in Python?

Python allows conversion of data types in two ways:-

  1. Implicit Type Conversion
    Here, python automatically converts the data in one type to another where users are not involved. The conversion always occurs towards higher data type.
    For example, when we add integer and float values, the resulting data will be in float
  2. Explicit Type Conversion
    There may be some cases when the user needs to define the data type. Python provides several built-in methods for typecasting one data type to another. The syntax for the explicit conversion is:-
    (datatype)(expression)

Example 1: Adding integer and float number using implicit type conversion

integer_number = 230
float_number = 10.2
sum = integer_number + float_number
print("Data type of integer_number:", type(integer_number))
print("Data type of float_number:", type(float_number))

print("Sum:", sum)
print("Data type of sum:", type(sum))

Output:

Data type of integer_number:
Data type of float_number:
Sum: 240.2
Data type of sum:

 

Example 2: Adding integer and string number using explicit type conversion

integer_number = 230
string_number = "102"
print("Data type of integer_number:", type(integer_number)) 
print("Data type of string_number before casting:", type(string_number)) 
string_number = int("102")
print("Data type of string_number after casting:", type(string_number)) 
sum = integer_number + string_number

print("Sum:", sum)
print("Data type of sum:", type(sum))

Output:

Data type of integer_number:
Data type of string_number before casting:
Data type of string_number after casting:
Sum: 332
Data type of sum:

What are data type functions available in Python?

# Function Description
1. int(x [,base]) Converts x to an integer. base specifies the base if x is a string.
2. long(x [,base] ) Converts x to a long integer. base specifies the base if x is a string.
3. float(x) Converts x to a floating-point number.
4. complex(real [,imag]) Creates a complex number.
5. str(x) Converts object x to a string representation
6. repr(x) Converts object x to an expression string.
7. eval(str) Evaluates a string and returns an object.
8. tuple(s) Converts s to a tuple.
9. list(s) Converts s to a list.
10. set(s) Converts s to a set.
11. dict(d) Creates a dictionary. d must be a sequence of (key,value) tuples.
12. frozenset(s) Converts s to a frozen set.
13 chr(x) Converts an integer to a character.
14. unichr(x) Converts an integer to a Unicode character.
15. ord(x) Converts a single character to its integer value.
16. hex(x) Converts an integer to a hexadecimal string.
17. oct(x) Converts an integer to an octal string.

 

Loading…