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

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."

Are F-strings good in Python? ›

Using f-strings, your code will not only be cleaner but also faster to write. With f-strings you are not only able to format strings but also print identifiers along with a value (a feature that was introduced in Python 3.8).

What does .2f mean in Python? ›

So %. 2f means to round up to two decimal places. You can play around with the code to see what happens as you change the number in the formatter.

How to pad f string in Python? ›

Padding f-strings in Python
  1. Right padding: This is the most common way to use padding format, right padding with spaces. ...
  2. Left Padding: Just use > to indicate the orientation. ...
  3. Center Padding: For center orientation use ^ . ...
  4. Type Formating: There is an especial formatting atributes called type. ...
  5. Format Specifications:
Feb 18, 2022

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.

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 does 10.2 f mean in Python? ›

The format 10.2f does not mean 10 digits before the decimal and two after. It means a total field width of 10. So there will be 7 digits before the decimal, the decimal which counts as one more, and 2 digits after.

What is 3.2 F in Python? ›

It means print as a floating point at least 3 wide and a precision of 2. This is a format specifier of a floating point number with 2 decimals and at least one digit left of the decimal point. The number 12.34567 would be displayed as 12.35.

What does 5.2 F mean in Python? ›

The 5.2f sets the minimum field with to 5 and the number of digits after the decimal place to 2.

How to give space in f-string? ›

In f-strings you can specify the width of the space you want the string to take up with :<5 after the variable name. The : is beginning the format specifier, the < is saying “left-justify” and the 5 is saying “reserve 5 columns of space for this variable”.

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.

How to format float in F-string Python? ›

To use Python's format specifiers in a replacement field, you separate them from the expression with a colon ( : ). As you can see, your float has been rounded to two decimal places. You achieved this by adding the format specifier . 2f into the replacement field.

What is the F-string concatenation in Python? ›

Concatenating Strings in Python Using f-Strings

Python f-strings are prefixed by the letter f and allow you to place variables to interpolate into square brackets. The variables are evaluated at run-time, and their string representation is placed into the string. print(f'Welcome to {website}!' )

What does print f mean in Python? ›

'f' in printf stands for formatted data printing, it is used for printing with formatted values as output.

What is the 1f in Python? ›

1f in Python lies in the number of decimal digits displayed in the output. :. 0f signifies that only the integer part of the number is desired, without any digits following the decimal point. Conversely, :. 1f indicates the desire to display one digit after the decimal point in the output.

What are strings in Python? ›

In Python, strings are used for representing textual data. A string is a sequence of characters enclosed in either single quotes ('') or double quotes (“”). The Python language provides various built-in methods and functionalities to work with strings efficiently.

Top Articles
Latest Posts
Article information

Author: Sen. Ignacio Ratke

Last Updated:

Views: 6348

Rating: 4.6 / 5 (56 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Sen. Ignacio Ratke

Birthday: 1999-05-27

Address: Apt. 171 8116 Bailey Via, Roberthaven, GA 58289

Phone: +2585395768220

Job: Lead Liaison

Hobby: Lockpicking, LARPing, Lego building, Lapidary, Macrame, Book restoration, Bodybuilding

Introduction: My name is Sen. Ignacio Ratke, I am a adventurous, zealous, outstanding, agreeable, precious, excited, gifted person who loves writing and wants to share my knowledge and understanding with you.