String Formatting
Learn to format strings in Python using various methods, including f-strings and the % operator.
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:
# Basic variable insertionname = "ABC"age = 30print(f"My name is {name} and I am {age} years old")# Arithmetic operationsa = 10b = 20print(f"The sum of {a} and {b} is {a + b}")# Specifying decimal precisionpi = 3.14159265359print(f"The value of pi is {pi:.2f}")print(f"The value of pi is {pi:.5f}")# Padding with zerosnumber1 = 5number2 = 79print(f"Number after padding {number1:03}")print(f"Number after padding {number2:03}")
Explanation
Here’s the code explanation:
Line 4: Uses an f-string to insert the values of the variables
name
andage
into the string. Here is the output after using an f-string:My name is ABC and I am 30 years old
Line 9: Uses an f-string to insert the values of the variables
a
andb
, 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 30
Line 13: Uses an f-string to insert the value of
pi
into the string, formatted to 2 decimal places. Here is the output after using an f-string:The value of pi is 3.14
...