Python Variable Casting


Python data type casting allows programmer to convert a value from one data type to another.

It allows you to change the type of data stored in a variable.

For example, you can convert a string to an integer or a float, or vice versa.

below are some examples of data type casting in Python :-

Converting a string to an integer:

str_number = "10"
int_number = int(str_number)
print(int_number)

Converting an integer to a string:

number = 10
str_number = str(number)
print(str_number)

Converting a float to an integer:

float_number = 10.5
int_number = int(float_number)
print(int_number)

Converting an integer to a float:

number = 10
float_number = float(number)
print(float_number)

Converting a string to a float:

float_number = 10.5
str_number = str(float_number)
print(str_number)

Converting a float to a string:

float_number = 10.5
str_number = str(float_number)
print(str_number)

Converting a string to a boolean:

str_bool = "True"
bool_value = bool(str_bool)
print(bool_value)

Converting an integer to a boolean:

number = 0
bool_value = bool(number)
print(bool_value)

Converting a boolean to an integer:

bool_value = True
number = int(bool_value)
print(number)

These are some common example to use.