F-Strings – Real Python (2024)

In this lesson, you’ll learn how to use f-strings, otherwise known as formatted string literals. They are available in Python 3.6 and above.

Here’s an example:

Python

>>> name = "Bob">>> age = 10>>> f"My name is {name}. I am {age} years old."'My name is Bob. I am 10 years old'

If you want to learn more, check out Python 3’s f-Strings: An Improved String Formatting Syntax.

00:00 This will be a short video on f-strings, otherwise known as formatted string literals. Normally, you might do something like this if you want to print a string out.

00:09 Let’s just say we have age = 10 and name = "Bob".

00:16 Let’s say we want to print out the string— print() string, "My name is Bob.

00:23 I am 10 years old." As you can see, I don’t really do this very often, that’s why it’s a little bit slower. I think the syntax is like that. Cool!

00:36 It worked. "My name is Bob. I am 10 years old". Okay. So, that’s been there since the beginning of time. You might also know .format() as a little bit cleaner way to do it.

00:46 You could do something like {1} and {0}, or you don’t even need these, I think, and it will still work. Or, if you wanted it to be cleaner and it to be a little bit more explicit, you would do something like this. So, those are all good ways to format strings.

01:03 Now, in Python 3.6 and above, you can use f-strings, which are very similar, but you just put the word f in front, and then instead of all this stuff, you just remove it.

01:16 So, it will actually evaluate what is in the curly brackets, and then sub in the variable names. You can do stuff like { age + 5 }, so they’re actually just expressions. I mean, you could do the same in the .format(), here, or in here, but then it’s all in one line and it’s very easy to see, just left-to-right, f"My name is {name}. I am {age}"—but you’re adding 5— "years old".

01:40 This is also useful for classes where you could have A class,

01:45 then define the __init__()—we’ll just use this example with name and age. self.name = name, self.age = age,

01:56 make a __str__() method—or, I guess a __repr__() method is a little bit more explicit, and if __str__() does not exist, it will actually call __repr__().

02:04 This is just a little bit easier. Return a multiline f-string, f""" My name is {self.name}. I am {self.age + 5} years old """.

02:23 Now, if we instantiate A with "Bob"—or, I guess we had variables name and age and then printed it out—we get a nice multiline string.

02:33 If you didn’t want the newlines and the spaces and stuff, you could just do something like this.

02:40 And if you wanted it all in one line, you could do…

02:50 Cool! There is just one case where you might not want to use formatted strings, and that is when you’re dealing with user input. If you’re letting your user type something and that goes into the formatted string, they can gain access to variables that they shouldn’t be.

03:04 I’ll link an article below that shows that example. I’ll also link an article that goes way in-depth into how f-strings work. But I think this is just a nice way to show the interviewer that you know how to use f-strings, and it saves you a little bit of time. In the next video, you’ll learn about sorting lists.

F-Strings – Real Python (1)

James Uejio RP Team on April 26, 2020

f-strings were added in 3.6: realpython.com/python-f-strings/

F-Strings – Real Python (2)

James Uejio RP Team on April 27, 2020

If you want to learn more, here is a Real Python walkthrough video on f-strings: Python 3’s f-Strings: An Improved String Formatting Syntax

Hi James, thank you for your tutorial. I’d appreciate if you could point me to the video or article that shows why it’s dangerous to use f-string with user input that you mention in this video. Thank you

F-Strings – Real Python (4)

Bartosz Zaczyński RP Team on March 31, 2021

@raulfz f-strings let you evaluate arbitrary Python expressions such as executing system commands or file removal:

import osf"{os.system('echo Hello > /home/user/file')}"f"{os.remove('/home/user/file')}"

Imagine what would happen if a rogue user provided malicious input for your placeholders.

F-Strings – Real Python (5)

Antonio B De Leon on Aug. 28, 2021

Yikes, that makes sense and is very scary.

F-Strings – Real Python (6)

szymon on March 7, 2022

Shouldn’t __repr__ return an object representation the way it could be reconstructed? Just like this:

def __repr__: return f"A(name={name!r}, age={age!r})"

Putting human-readable string in there might teach some bad habits for less experienced programmers.

F-Strings – Real Python (7)

Bartosz Zaczyński RP Team on March 7, 2022

@szymon It’s not an absolute requirement, but you’re right. In general, .__repr__() should return a piece of Python code that can be evaluated to recreate an object with the same value.

F-Strings – Real Python (8)

Lucas Ribeiro on Sept. 17, 2022

About the arbitrary execution, it could be solved if I enforce str(), e.g.:

f'My name is {str(input())}'os.system('echo Hello > /home/user/file'Out[10]: "My name is os.system('echo Hello > /home/user/file'"

Using print %s already enforces the input to be a string as well:

print ("My name is %s" % (input()))"os.system('echo Hello > /home/user/file'"My name is "os.system('echo Hello > /home/user/file'"

Become a Member to join the conversation.

F-Strings – Real Python (2024)

FAQs

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

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

You just embed the desired objects or expressions in your string literal using curly brackets. It's important to note that Python evaluates f-strings at runtime. So, in this example, both name and age are interpolated into the string literal when Python runs the line of code containing the f-string.

What is the alternative to F-string in Python? ›

Alternative Formatting Methods. While Python's f-string formatting is a powerful and efficient tool, it's not the only way to format strings in Python. Two other popular methods are the str. format() method and the % operator.

What are the F strings 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.

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

Why are F strings faster? ›

Conciseness: F-strings provide a concise syntax for string formatting, reducing the amount of code required compared to other methods.

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.

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.

Why do we use print f in Python? ›

A string prefixed with 'f' or 'F' and writing expressions as {expression} is a way to format string, which can include the value of Python expressions inside it. f-string in python lets you format data for printing using string templates.

Can we use F-string in dictionary Python? ›

Python 3.6+ has introduced f-strings support in which keys of a dictionary can be used to format a string. In this approach, you need to place the f prefix before the string and place the key of the dictionary inside the curly braces { }.

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 Matlab equivalent of Python F-string? ›

Matlab doesn't have a direct equivalent to Python's f-strings, but you can achieve similar functionality using string formatting or concatenation.

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}!' )

How to round numbers in f-strings? ›

Rounding Numbers With F-Strings

F-strings can also be used to round numbers to a specific precision, using the round() function. To round a number using f-strings, simply include the number inside the curly braces, followed by a colon and the number of decimal places to round to.

How do you make an F-string have no new line in Python? ›

Using Backslashes

The backslashes tell Python to ignore the newline characters in the code and join the f-strings into one single line. Using backslashes, you can create multiline strings with f-strings without having to use triple quotes or escape characters. This can make your code more compact and efficient.

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.

Can you use F strings 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.

Does Python 3.8 have F strings? ›

The = specifier in f-strings (Python 3.8 and later)

You can also specify format specification strings and expressions with the = specifier. This also applies to lists and dictionaries.

Can we use F string in dictionary Python? ›

Python 3.6+ has introduced f-strings support in which keys of a dictionary can be used to format a string. In this approach, you need to place the f prefix before the string and place the key of the dictionary inside the curly braces { }.

References

Top Articles
Latest Posts
Article information

Author: Gregorio Kreiger

Last Updated:

Views: 5958

Rating: 4.7 / 5 (77 voted)

Reviews: 84% of readers found this page helpful

Author information

Name: Gregorio Kreiger

Birthday: 1994-12-18

Address: 89212 Tracey Ramp, Sunside, MT 08453-0951

Phone: +9014805370218

Job: Customer Designer

Hobby: Mountain biking, Orienteering, Hiking, Sewing, Backpacking, Mushroom hunting, Backpacking

Introduction: My name is Gregorio Kreiger, I am a tender, brainy, enthusiastic, combative, agreeable, gentle, gentle person who loves writing and wants to share my knowledge and understanding with you.