Open In App

f-strings in Python

Last Updated : 19 Jun, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Python offers a powerful feature called f-strings (formatted string literals) to simplify string formatting and interpolation. f-strings is introduced in Python 3.6 it provides a concise and intuitive way to embed expressions and variables directly into strings. The idea behind f-strings is to make string interpolation simpler. 

How to use f-strings in Python

To create an f-string, prefix the string with the letter “ f ”. The string itself can be formatted in much the same way that you would with str.format(). F-strings provide a concise and convenient way to embed Python expressions inside string literals for formatting. 

Print Variables using f-string in Python

In the below example, we have used the f-string inside a print() method to print a string. We use curly braces to use a variable value inside f-strings, so we define a variable ‘val’ with ‘Geeks’ and use this inside as seen in the code below ‘val’ with ‘Geeks’. Similarly, we use the ‘name’ and the variable inside a second print statement.

Python
# Python3 program introducing f-string
val = 'Geeks'
print(f"{val}for{val} is a portal for {val}.")


name = 'Om'
age = 22
print(f"Hello, My name is {name} and I'm {age} years old.")

Output

GeeksforGeeks is a portal for Geeks.
Hello, My name is Om and I'm 22 years old.

Print date using f-string in Python

In this example, we have printed today’s date using the datetime module in Python with f-string. For that firstly, we import the datetime module after that we print the date using f-sting. Inside f-string ‘today’ assigned the current date and %B, %d, and %Y represents the full month, day of month, and year respectively.

Python
# Prints today's date with help
# of datetime library
import datetime

today = datetime.datetime.today()
print(f"{today:%B %d, %Y}")

Output

May 23, 2024

Note: F-strings are faster than the two most commonly used string formatting mechanisms, which are % formatting and str.format(). 

Quotation Marks in f-string in Python

To use any type of quotation marks with the f-string in Python we have to make sure that the quotation marks used inside the expression are not the same as quotation marks used with the f-string.

Python
print(f"'GeeksforGeeks'")

print(f"""Geeks"for"Geeks""")

print(f'''Geeks'for'Geeks''')

Output

'GeeksforGeeks'
Geeks"for"Geeks
Geeks'for'Geeks

Evaluate Expressions with f-Strings in Python

We can also evaluate expressions with f-strings in Python. To do so we have to write the expression inside the curly braces in f-string and the evaluated result will be printed as shown in the below code’s output.

Python
english = 78
maths = 56
hindi = 85

print(f"Ram got total marks {english + maths + hindi} out of 300")

Output

Ram got total marks 219 out of 300

Errors while using f-string in Python

Backslashes in f-string in Python

In Python f-string, Backslash Cannot be used in format string directly.

Python
f"newline: {ord('\n')"

Output

Hangup (SIGHUP)
File "Solution.py", line 1
f"newline: {ord('\n')"
^
SyntaxError: f-string expression part cannot include a backslash

However, we can put the backslash into a variable as a workaround though :

Python
newline = ord('\n')

print(f"newline: {newline}")

Output

newline: 10

Inline comments in f-string in Python

We cannot use comments inside F-string expressions. It will give an error:

Python
f"GeeksforGeeks is {5*2 + 3 #geeks-5} characters."

Output:

Hangup (SIGHUP)
File "Solution.py", line 1
f"GeeksforGeeks is {5*2 + 3 #geeks-5} characters."
^
SyntaxError: f-string expression part cannot include '#'

Printing Braces using f-string in Python

If we want to show curly braces in the f-string’s output then we have to use double curly braces in the f-string. Note that for each single pair of braces, we need to type double braces as seen in the below code.

Python
# Printing single braces
print(f"{{Hello, Geek}}")

# Printing double braces
print(f"{{{{Hello, Geek}}}}")

Output

{Hello, Geek}
{{Hello, Geek}}

Printing Dictionaries key-value using f-string in Python

While working with dictionaries, we have to make sure that if we are using double quotes (“) with the f-string then we have to use single quote (‘) for keys inside the f-string in Python and vice-versa. Otherwise, it will throw a syntax error.

Python
Geek = { 'Id': 112,
         'Name': 'Harsh'}

print(f"Id of {Geek["Name"]} is {Geek["Id"]}")

Output

Hangup (SIGHUP)
File "Solution.py", line 4
print(f"Id of {Geek["Name"]} is {Geek["Id"]}")
^
SyntaxError: invalid syntax

Using the same type of quotes for f-string and key

Python
Geek = { 'Id': 100,
         'Name': 'Om'}

print(f"Id of {Geek['Name']} is {Geek['Id']}")

Output

Id of Om is 100

Frequently Asked Questions on F-Strings in Python – FAQs

What are f-strings in Python?

f-strings (formatted string literals) are a way to embed expressions inside string literals in Python, using curly braces {}. They provide an easy and readable way to format strings dynamically.

name = "Alice"
age = 30
sentence = f"My name is {name} and I am {age} years old."
print(sentence)
Output:
My name is Alice and I am 30 years old.

How to use .2f in Python?

.2f is used to format floating-point numbers to two decimal places when printing or formatting strings. For example:

num = 3.14159
formatted = f"{num:.2f}"
print(formatted) # Output: 3.14

How to use F-string in JSON Python?

You can embed f-strings inside JSON strings by using them directly where needed:

name = "Alice"
age = 30
json_data = f'{{ "name": "{name}", "age": {age} }}'
print(json_data)
Output:
{ "name": "Alice", "age": 30 }

Note the double curly braces {{ }} around the f-string to escape them in the JSON string.

Can we use F-string in input Python?

Yes, you can use f-strings with input() to prompt the user and dynamically format strings based on input values:

name = input("Enter your name: ")
message = f"Hello, {name}!"
print(message)

What is the alternative to F-string in Python?

Before f-strings were introduced in Python 3.6, you could format strings using str.format() method or using % formatting (old-style formatting). For example:

name = "Alice"
age = 30
sentence = "My name is {} and I am {} years old.".format(name, age)
print(sentence)
Output:
My name is Alice and I am 30 years old.

However, f-strings are generally preferred due to their readability, simplicity, and efficiency.



Previous Article
Next Article

Similar Reads

Python | Remove empty strings from list of strings
In many scenarios, we encounter the issue of getting an empty string in a huge amount of data and handling that sometimes becomes a tedious task. Let's discuss certain way-outs to remove empty strings from list of strings. Method #1: Using remove() This particular method is quite naive and not recommended use, but is indeed a method to perform this
7 min read
Python | Tokenizing strings in list of strings
Sometimes, while working with data, we need to perform the string tokenization of the strings that we might get as an input as list of strings. This has a usecase in many application of Machine Learning. Let's discuss certain ways in which this can be done. Method #1 : Using list comprehension + split() We can achieve this particular task using lis
3 min read
Python - Find all the strings that are substrings to the given list of strings
Given two lists, the task is to write a Python program to extract all the strings which are possible substring to any of strings in another list. Example: Input : test_list1 = ["Geeksforgeeks", "best", "for", "geeks"], test_list2 = ["Geeks", "win", "or", "learn"] Output : ['Geeks', 'or'] Explanation : "Geeks" occurs in "Geeksforgeeks string as subs
5 min read
Convert Strings to Numbers and Numbers to Strings in Python
In Python, strings or numbers can be converted to a number of strings using various inbuilt functions like str(), int(), float(), etc. Let's see how to use each of them. Example 1: Converting a Python String to an int: C/C++ Code # code # gfg contains string 10 gfg = "10" # using the int(), string is auto converted to int print(int(gfg)+2
2 min read
Interesting facts about strings in Python | Set 2 (Slicing)
Creating a String Strings in Python can be created using single quotes or double quotes or even triple quotes. # Python Program for # Creation of String # Creating a String # with single Quotes String1 = 'Welcome to the Geeks World' print("String with the use of Single Quotes: ") print(String1) # Creating a String # with double Quotes String1 = "I'
4 min read
Python | Set 3 (Strings, Lists, Tuples, Iterations)
In the previous article, we read about the basics of Python. Now, we continue with some more python concepts. Strings in Python: A string is a sequence of characters that can be a combination of letters, numbers, and special characters. It can be declared in python by using single quotes, double quotes, or even triple quotes. These quotes are not a
3 min read
Python | Converting all strings in list to integers
Interconversion between data types is facilitated by python libraries quite easily. But the problem of converting the entire list of strings to integers is quite common in the development domain. Let's discuss a few ways to solve this particular problem. Converting all strings in list to integers Using eval()Python eval() function parse the express
7 min read
Using Counter() in Python to find minimum character removal to make two strings anagram
Given two strings in lowercase, the task is to make them Anagram. The only allowed operation is to remove a character from any string. Find minimum number of characters to be deleted to make both the strings anagram? If two strings contains same data set in any order then strings are called Anagrams. Examples: Input : str1 = "bcadeh" str2 = "hea" O
3 min read
Python code to print common characters of two Strings in alphabetical order
Given two strings, print all the common characters in lexicographical order. If there are no common letters, print -1. All letters are lower case. Examples: Input : string1 : geeks string2 : forgeeks Output : eegks Explanation: The letters that are common between the two strings are e(2 times), g(1 time), k(1 time) and s(1 time). Hence the lexicogr
2 min read
Python Program to Check if Two Strings are Anagram
Question: Given two strings s1 and s2, check if both the strings are anagrams of each other. Examples: Input : s1 = "listen" s2 = "silent" Output : The strings are anagrams. Input : s1 = "dad" s2 = "bad" Output : The strings aren't anagrams.Solution:Method #1 : Using sorted() function Python provides a inbuilt function sorted() which does not modif
5 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg