Data type conversion
In some specific scenario, the data type actually can be converted to another type.
Ex: int -> str
Scenario that we need data type conversion
read a number from a file, bydefault it's type is str, we need toconvertit to inthandling input() value, bydefault it's str, we needconvertit's value accordingly
Format
py
int(x) # convert x to int type
str(x) # convert x to str type
float(x) # convert x to float type
Use with variableorprint directlyto use it.
Usage
data-type-conversion.py
py
str_number = "123"
# Convert string to integer
int_number = int(str_number)
print(type(int_number)) # Output: <class 'int'>
float_number = 3.14
# Convert float to integer
int_from_float = int(float_number)
print(int_from_float) # Output: 3
# Convert integer to string
str_from_int = str(int_number)
print(str_from_int) # Output: '123'
# Convert float to string
str_from_float = str(float_number)
print(str_from_float) # Output: '3.14'Results:
<class 'int'>
3
123
3.14