Python Casting - How to change the variable type?

/ #Python


Sometimes we need to convert a string to an integer, a float to a string, etc.

str() - Strings

# Define an integer and a float
age = 32
weight = 68.4

# Convert to string
string_age = str(age). # Will be "32"
string_weight = str(weight)  # Will be "68.4"

int() - Integers

# Define a string and a float
age = "32"
weight = 68.4

# Convert to integer
int_age = int(age). # Will be 32
int_weight = int(weight)  # Will be 68

float() - Floats

# Define an integer and two strings
age = 32
weight = "68.4"
height = "178"

# Convert to float
float_age = float(age)  # Will be 32.0
float_weight = float(weight)  # Will be 68.4
float_height = float(height)  # Will be 178.0

Errors

If you try to convert a value that can't be converted/casted, you will get an error. For example "int("Hello")" will not work.

Comments

No comments yet...

Add comment

Info

Please log in to comment!

Newsletter

Subscribe to my weekly newsletter. One time per week I will send you a short summary of the tutorials I have posted in the past week.