w3resource

How do you convert one data type to another in Python?

Dynamic Typing in Python: Handling Variable Types at Runtime

Python converts one data type to another using explicit type conversions (casting) or implicit type conversions.

Explicit Type Conversions (Casting): Explicit type conversions involve using specific functions to convert data from one type to another. Python provides built-in type conversion functions, such as int(), float(), str(), etc.

Here are some examples of explicit type conversions:

Converting to int:

Code:


str_num = "200"
int_num = int(str_num)
print(str_num, type(str_num))  # Output: 200 <class 'str'>

Output:

200 <class 'str'> 

Converting to float:

Code:

str_num = "200.13"
float_num = float(str_num)
print(str_num, type(str_num)) # Output: 200.13 <class 'str'>

Output:

200.13 <class 'str'>

Converting to str:

Code:

x = 456
x_str = str(x)
print(x_str, type(x_str))  # Output: '456' <class 'str'>

Output:

456 <class 'str'>

Implicit Type Conversions:

Implicit type conversions occur automatically during certain operations when data types are incompatible. Python coerces to ensure the operation is carried out smoothly.

Here are some examples of implicit type conversions:

Integer and Float conversion:

Code:

a = 10
b = 3.14
result = a + b
print(result, type(result))  # Output: 13.14 <class 'float'>

Output:

13.14 <class 'float'>

String and Integer conversion:

Code:

str_num = "234"
x = 10
result_str = str_num + str(x)
print(result_str, type(result_str))  # Output: '23410' <class 'str'>

Output:

23410 <class 'str'> 

Boolean and Integer Conversion:

Code:

is_employee = True
x = 1
result = is_employee + x
print(result, type(result))  # Output: 2 <class 'int'>

Output:

2 <class 'int'>

In the first example, Python implicitly converts the integer 'a' to a float to add to the float 'b'. In the second example, the integer 'x' is implicitly converted to a string to concatenate it with the string 'num_str'. In the third example, Python transforms the boolean 'is_employee' to an integer (True is treated as 1, and False as 0) before adding it to 'x'.



Follow us on Facebook and Twitter for latest update.