String Formatting
Learn to format strings in Python using various methods, including f-strings and the % operator.
We'll cover the following...
String formatting in Python refers to the process of embedding variables or expressions within a string. It allows inserting values into a string at runtime, enabling greater flexibility.
Formatting with f-strings
The f-strings introduces Python 3.6 , also known as formatted string literals, which provide a simple yet understandable approach to format strings. With f-strings, expressions may be embedded directly into string literals, making formatting easier. Here’s an example illustrating the use of the f-strings:
Explanation
Here’s the code explanation:
Line 4: Uses an f-string to insert the values of the variables
nameandageinto the string. Here is the output after using an f-string:My name is ABC and I am 30 years oldLine 9: Uses an f-string to insert the values of the variables
aandb, and the result of the arithmetic operationa + b, into the string. Here is the output after using an f-string:The sum of 10 and 20 is 30Line 13: Uses an f-string to insert the value of
piinto the string, formatted to 2 decimal places. Here is the output after using an f-string:The value of pi is 3.14...