Google News
logo
Python Program to Casting - Strings
In the following example of Python program that demonstrates how to cast a variable to a string :
Program :
# Casting - Strings
x = 3.5
print("Original value:", x)
print("Type of x:", type(x))

x = str(x)
print("Casted value:", x)
print("Type of x:", type(x))
Output :
Original value: 3.5
Type of x: <class 'float'>
Casted value: 3.5
Type of x: <class 'str'>
In the above program, we start by assigning the value `3.5` to the variable `x`. We then use the `print()` function to print the original value of `x`, as well as its type.

Next, we use the `str()` function to cast `x` to a string. We assign the result of the `str()` function back to the variable `x`.

Finally, we use the `print()` function to print the casted value of `x`, as well as its type.

As you can see, the `str()` function has converted the float value `3.5` to the string value `'3.5'`.