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.
Submitted by IncludeHelp, on June 14, 2020

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:

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

Example 1:

# 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:

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:

# 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:

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:

# 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:

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

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.