Why converting integer or float to string in Python?
In Python, converting an integer or a float to a string is often necessary for the following reasons:
String Concatenation: To concatenate an integer or a float with a string, you need to convert the integer or float to a string first.
Formatting Output: To include an integer or a float in a formatted string, you need to convert it to a string.
Converting integer or float to string using str() function
In Python, you can convert an integer or a float to a string using str()
built-in function.
Please take a closer look at the following example:
Example of str() function
xxxxxxxxxx
# Convert integer to string
integer_variable = 1225 # Integer data
converted_integer_to_string = str(integer_variable) # Using the str() function
print("Converted integer to string: " + converted_integer_to_string)
# Convert float to string
floatl_variable = 123.45 # float data
converted_float_to_string = str(floatl_variable) # Using the str() function
print("Converted float to string: " + converted_float_to_string)
Output of the above example
Converted integer to string: 1225 Converted float to string: 123.45
Converting integer or float to string using formatted strings (f-strings)
In Python, you can convert an integer or a float to a string using formatted strings (f-strings).
This is especially useful when you want to include values in a larger string.
To create a f-string, first write f""
and put your text inside the double quotes.
The f-string allows you to embed expressions inside curly braces {}
. In the following example, int variable x is placed inside the curly brace: f"Integer {x} is converted to string"
Please take a closer look at the following example:
Example of formatted strings (f-strings)
xxxxxxxxxx
x = 55 # int data
integer_string = f"Integer {x} is converted to string"
print(integer_string)
#Another example
age = 42 # int data type
height = 1.76 # float data type
print(f"John is {age} years old and his height is {height} meter")
Output of the above example
Integer 55 is converted to string John is 42 years old and his height is 1.76 meter