Skip to content

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, by default it's type is str, we need to convert it to int
  • handling input() value, by default it's str, we need convert it'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 variable or print directly to 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