f-strings in Python 3: Formatted string literals

Python | f-strings (Literal String Interpolation): In this tutorial, we are going to learn about formatting the strings using f-strings formatting with examples. By IncludeHelp Last updated : January 03, 2024

f-strings Formatting (Literal String Interpolation)

In Python 3.6, a new feature for string formatting is introduced that is "Literal String Interpolation" also knows as "f-strings formatting".

Formatting strings are very easy by f-strings, we have to prefix the literal f before the string to be printed. That's why it is called f-strings formatting. To print the values of the objects (variables) – pass the variable name within the curly braces {}.

Syntax

The syntax of f-strings formatting (literal string interpolation) in Python is:

print(f"{variables}")
or
print(f'{variables}')

f-strings Formatting Examples

Practice these examples to understand the concept of f-strings formatting (literal string interpolation) in Python.

Example 1

Print formatted strings using f-string.

# Python program to demonstrate the 
# example of f-strings formatting

a = 10
b = 123.45
c = 'X'
d = "Hello"

# printing one by one
print("Printing one by one...")
print(f"a = {a}")
print(f"b = {b}")
print(f"c = {c}")
print(f"d = {d}")
print() # prints new line

# printing together 
print("Printing together...")
print(f"a = {a}, b = {b}, c = {c}, d = {d}")

Output

The output of the above example is:

Printing one by one...
a = 10
b = 123.45
c = X
d = Hello

Printing together...
a = 10, b = 123.45, c = X, d = Hello

Example 2

Print formatted strings using f-string.

# Python program to demonstrate the 
# example of f-strings formatting

name = "Mike"
age = 21
country = 'USA'

# printing one by one
print("Printing one bye one...")
print(f"Name : {name}")
print(f"Age  : {age}")
print(f"Country : {country}")
print() # prints new line

# printing without messages
print("Printing without messages...")
print(f"{name} {age} {country}")
print()

# printing together 
print("Printing together...")
print(f"Name: {name}, Age: {age}, Country: {country}")

Output

The output of the above example is:

Printing one bye one...
Name : Mike
Age  : 21
Country : USA

Printing without messages...
Mike 21 USA

Printing together...
Name: Mike, Age: 21, Country: USA

Example 3

Print table of a number using f-string.

# Printing table using f-strings

a = 10

# printing the table
print(f"Table of {a}:")
for i in range(1, 11):
  print(f"{a} x {i} = {a*i}")

Output

The output of the above example is:

Table of 10:
10 x 1 = 10
10 x 2 = 20
10 x 3 = 30
10 x 4 = 40
10 x 5 = 50
10 x 6 = 60
10 x 7 = 70
10 x 8 = 80
10 x 9 = 90
10 x 10 = 100

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.