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
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)
Output of the above example
Integer 55 is converted to string John is 42 years old and his height is 1.76 meter