...

/

String Formatting

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:

Press + to interact
# Basic variable insertion
name = "ABC"
age = 30
print(f"My name is {name} and I am {age} years old")
# Arithmetic operations
a = 10
b = 20
print(f"The sum of {a} and {b} is {a + b}")
# Specifying decimal precision
pi = 3.14159265359
print(f"The value of pi is {pi:.2f}")
print(f"The value of pi is {pi:.5f}")
# Padding with zeros
number1 = 5
number2 = 79
print(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 and age 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 and b, and the result of the arithmetic operation a + 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 ...