Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
Python String Methods
Next article icon

Python offers a powerful feature calledf-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 withstr.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'andthevariable inside a second print statement.

Python
# Python3 program introducing f-stringval='Geeks'print(f"{val}for{val} is a portal for{val}.")name='Om'age=22print(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 thedatetimemodule in Python withf-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 thefull month,day of month, andyear respectively.

Python
# Prints today's date with help# of datetime libraryimportdatetimetoday=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=78maths=56hindi=85print(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 bracesprint(f"{{Hello, Geek}}")# Printing double bracesprint(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

Improve
Article Tags :
Practice Tags :

Similar Reads

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood ourCookie Policy &Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp