f-strings in Python - GeeksforGeeks (2024)

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-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 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 libraryimport datetimetoday = 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

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.



T

Tushar Nema

Improve

Previous Article

Python String format() Method

Next Article

Python String Exercise

Please Login to comment...

f-strings in Python - GeeksforGeeks (2024)

FAQs

Are F-strings good in Python? ›

Python f-strings provide a quick way to interpolate and format strings. They're readable, concise, and less prone to error than traditional string interpolation and formatting tools, such as the .format() method and the modulo operator ( % ). An f-string is also a bit faster than those tools!

What is an f-string 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."

Why put f before string Python? ›

The release of Python version 3.6 introduced formatted string literals, simply called “f-strings.” They are called f-strings because you need to prefix a string with the letter 'f' to create an f- string. The letter 'f' also indicates that these strings are used for formatting.

How do you escape an F-string in Python? ›

Python f-string Escaping Characters

For this purpose, we make use of escape characters in f-string. To escape a curly bracket, we double the character. While a single quote is escaped using a backslash.

What are the disadvantages of F strings? ›

From the user's perspective, the current f-string implementation imposes some limitations:
  • Reusing quotes or string delimiters isn't possible.
  • Embedding backslashes isn't possible, which means you can't use escape characters.
  • Adding inline comments is forbidden.
Jul 26, 2023

What can I use instead of F-string in Python? ›

Python has several tools for string interpolation that support many formatting features. In modern Python, you'll use f-strings or the .format() method most of the time. However, you'll see the modulo operator ( % ) being used in legacy code.

When were f-strings added to Python? ›

Python f-strings or formatted strings are the new way to format strings. This feature was introduced in Python 3.6 under PEP-498.

Can we use F string in input Python? ›

In Python, we use the input() function to take input from the user. Whatever you enter as input, the input function converts it into a string. If you enter an integer value still input() function converts it into a string.

What is the advantage of using placeholders or f-strings in output statements? ›

f-strings have an advantage over format specifiers: we don't need to worry about data types of input variables. We also don't need to worry about the order of input variables as we have to specify variable names directly into the placeholders.

Why not use F-string in logging Python? ›

Using f-strings to format a logging message requires that Python eagerly format the string, even if the logging statement is never executed (e.g., if the log level is above the level of the logging statement), whereas using the extra keyword argument defers formatting until required.

How does F write work in Python? ›

The data to be written is stored in a list called data. The for statement is used to loop over each line of data in the list. The f. write(line + '\n') statement writes each line of data to the file with a newline character (\n) at the end.

Why print F is used in Python? ›

printf and h. fprint return the number of characters printed. The parentheses around the print argument are supplied in this way to allow it to work with both Python 2 and Python 3. This is not an identical replacement because it does not return the number of characters.

How does f-string work in Python? ›

In Python source code, an f-string is a literal string, prefixed with 'f', which contains expressions inside braces. The expressions are replaced with their values.

How do you single quote an F-string in Python? ›

🔹 Quotation Marks in F-strings

When using quotation marks inside an f-string, you can use either single quotes ('') or double quotes (“”). This allows you to include quotes within your strings without causing syntax errors.

How do you remove spaces from an F-string in Python? ›

How to Remove Spaces from a String in Python
  1. Using replace()
  2. Using translate()
  3. Using lstrip() function.
  4. Using rstrip() function.
  5. Using isspace() method.
  6. Using Regex and itertools.
  7. Using split() and strip() function.
  8. Using NumPy.
Dec 21, 2023

Are Python F strings secure? ›

For example, f-strings have similar syntax to str. format() but, because f-strings are literals and the inserted values are evaluated separately through concatenation-like behavior, they are not vulnerable to the same attack (source B).

Why are F strings faster? ›

In conclusion, f-strings are faster than str. format() because they are evaluated at a phase that is closer to compile-time within Python's interpretation process, which reduces the amount of work that needs to be done at runtime. This makes f-strings a faster and more efficient way to format strings in Python.

What is the best string formatting in Python? ›

The format() method can still be used, but f-strings are faster and the preferred way to format strings.

Top Articles
Latest Posts
Article information

Author: Kareem Mueller DO

Last Updated:

Views: 5357

Rating: 4.6 / 5 (66 voted)

Reviews: 81% of readers found this page helpful

Author information

Name: Kareem Mueller DO

Birthday: 1997-01-04

Address: Apt. 156 12935 Runolfsdottir Mission, Greenfort, MN 74384-6749

Phone: +16704982844747

Job: Corporate Administration Planner

Hobby: Mountain biking, Jewelry making, Stone skipping, Lacemaking, Knife making, Scrapbooking, Letterboxing

Introduction: My name is Kareem Mueller DO, I am a vivacious, super, thoughtful, excited, handsome, beautiful, combative person who loves writing and wants to share my knowledge and understanding with you.