f-strings in Python - Explained with Code Examples

When you're formatting strings in Python, you're probably used to using the format() method.

But in Python 3.6 and later, you can use f-Strings instead. f-Strings, also called formatted string literals, have a more succinct syntax and can be super helpful in string formatting.

In this tutorial, you'll learn about f-strings in Python, and a few different ways you can use them to format strings.

What are f-Strings in Python?

Strings in Python are usually enclosed within double quotes ("" ) or single quotes (''). To create f-strings, you only need to add an f  or an F before the opening quotes of your string.

For example, "This" is a string whereas f"This" is an f-String.

How to Print Variables using Python f-Strings

When using f-Strings to display variables, you only need to specify the names of the variables inside a set of curly braces {}. And at runtime, all variable names will be replaced with their respective values.

If you have multiple variables in the string, you need to enclose each of the variable names inside a set of curly braces.

The syntax is shown below:

f"This is an f-string {var_name} and {var_name}."

▶ Here's an example.

You have two variables, language and school, enclosed in curly braces inside the f-String.

language = "Python"
school = "freeCodeCamp"
print(f"I'm learning {language} from {school}.")

Let's take a look at the output:

I'm learning Python from freeCodeCamp.

Notice how the variables language and school have been replaced with Python and freeCodeCamp, respectively.

How to Evaluate Expressions with Python f-Strings

As f-Strings are evaluated at runtime, you might as well evaluate valid Python expressions on the fly.

▶ In the example below, num1 and num2 are two variables. To calculate their product, you may insert the expression num1 * num2 inside a set of curly braces.

num1 = 83
num2 = 9
print(f"The product of {num1} and {num2} is {num1 * num2}.")

Notice how num1 * num2 is replaced by the product of num1 and num2 in the output.

The product of 83 and 9 is 747.

I hope you're now able to see the pattern.

In any f-String, {var_name}, {expression} serve as placeholders for variables and expressions, and are replaced with the corresponding values at runtime.

Head over to the next section to learn more about f-Strings.

How to Use Conditionals in Python f-Strings

Let's start by reviewing Python's if..else statements. The general syntax is shown below:

if condition:
  # do this if condition is True <true_block>
  # do this if condition is False <false_block>

Here, condition is the expression whose truth value is checked.

  • If the condition evaluates to True, the statements in the if block (<true_block>) are executed.
  • If the condition evaluates to False, the statements in the else block (<false_block>) are executed.

There's a more succinct one-line equivalent to the above if..else blocks. The syntax is given below:

<true_block> if <condition> else <false_block>

In the above syntax,<true block> is what's done when the condition is True, and <false_block> is the statement to be executed when the condition is False.

This syntax may seem a bit different if  you haven't seen it before. If it makes things any simpler, you may read it as, "Do this if condition is True; else, do this".

This is often called the ternary operator in Python as it takes 3 operands in some sense – the true block, the condition under test, and the false block.

▶ Let's take a simple example using the ternary operator.

Given a number num, you'd like to check if it's even. You know that a number is even if it's evenly divisible by 2. Let's use this to write our expression, as shown below:

num = 87;
print(f"Is num even? {True if num%2==0 else False}")

In the above code snippet,

  • num%2==0 is the condition.
  • If the condition is True, you just return True indicating that num is indeed even, and False otherwise.
Is num even? False

In the above example, num is 87, which is odd. Hence the conditional statement in the f-String is replaced with False.

How to Call Methods with Python f-Strings

So far, you've only seen how to print values of variables, evaluate expressions, and use conditionals inside f-Strings. And it's time to level up.

▶ Let's take the following example:

author = "jane smith"
print(f"This is a book by {author}.")

The above code prints out This is a book by jane smith.

Wouldn't it be better if it prints out This is a book by Jane Smith. instead? Yes, and in Python, string methods return modified strings with the requisite changes.

The title() method in Python returns a new string that's formatted in the title case - the way names are usually formatted (First_name Last_name).

To print out the author's name formatted in title case, you can do the following:

  • use the title() method on the string author,
  • store the returned string in another variable, and
  • print it using an f-String, as shown below:
author = "jane smith"
a_name = author.title()
print(f"This is a book by {a_name}.")

This is a book by Jane Smith.

However, you can do this in just one step with f-Strings. You only need to call the title() method on the string author inside the curly braces within the f-String.

author = "jane smith"
print(f"This is a book by {author.title()}.")

When the f-String is parsed at runtime,

  • the title() method is called on the string author, and
  • the returned string that's formatted in title case is printed out.

You can verify that in the output shown below.

This is a book by Jane Smith.

You can place method calls on any valid Python object inside the curly braces, and they'll work just fine.

How to Call Functions Inside Python f-Strings

In addition to calling methods on Python objects, you can also call functions inside f-Strings. And it works very similarly to what you've seen before.

Just the way variable names are replaced by values, and expressions are replaced with the result of evaluation, function calls are replaced with the return value from the function.

▶ Let's take the function choice() shown below:

def choice(c):
  if c%2 ==0:
    return "Learn Python!"
    return "Learn JavaScript!"

The above function returns "Learn Python!" if it's called with an even number as the argument. And it returns "Learn JavaScript!" when the argument in the function call is an odd number.

▶ In the example shown below, you have an f-String that has a call to the choice function inside the curly braces.

print(f"Hello Python, tell me what I should learn. {choice(3)}")

As the argument was an odd number (3), Python suggests that you learn JavaScript, as indicated below:

Hello Python, tell me what I should learn. Learn JavaScript!

If you call the function choice() with an even number, you see that Python tells you to learn Python instead. 🙂

print(f"Hello Python, tell me what I should learn. {choice(10)}")
Hello Python, tell me what I should learn. Learn Python!

And that ends our tutorial on a happy note!


In this tutorial, you've learned how you can use f-Strings to:

  • print values of variables,
  • evaluate expressions,
  • call methods on other Python objects, and
  • make calls to Python functions.

Original article at https://www.freecodecamp.org

Related Posts

Explains string formatting using the format() method.


What is GEEK

Buddha Community

f-strings in Python - Explained with Code Examples
Ray  Patel

Ray Patel


Lambda, Map, Filter functions in python

Welcome to my Blog, In this article, we will learn python lambda function, Map function, and filter function.

Lambda function in python: Lambda is a one line anonymous function and lambda takes any number of arguments but can only have one expression and python lambda syntax is

Syntax: x = lambda arguments : expression

Now i will show you some python lambda function examples:

#python #anonymous function python #filter function in python #lambda #lambda python 3 #map python #python filter #python filter lambda #python lambda #python lambda examples #python map

Ray  Patel

Ray Patel


50+ Basic Python Code Examples

List, strings, score calculation and more…

1. How to print “Hello World” on Python?

2. How to print “Hello + Username” with the user’s name on Python?

3. How to add 2 numbers entered on Python?

4. How to find the Average of 2 Entered Numbers on Python?

5. How to calculate the Entered Visa and Final Grade Average on Python?

6. How to find the Average of 3 Written Grades entered on Python?

7. How to show the Class Pass Status (PASSED — FAILED) of the Student whose Written Average Has Been Entered on Python?

8. How to find out if the entered number is odd or even on Python?

9. How to find out if the entered number is Positive, Negative, or 0 on Python?

#programming #python #coding #50+ basic python code examples #python programming examples #python code

Udit Vashisht


Python f-strings - The Ultimate Usage Guide

Python f-strings are the fastest string formatting option available on Python. It is robust, easy to read, concise and less prone to errors. If you are using Python 3.6+, you must switch to Python f-strings. In this detailed guide, we have covered all the concepts of Python f-strings

#python-f-strings #f-strings #python-f-strings-padding #python

Shardul Bhatt

Shardul Bhatt


Why use Python for Software Development

No programming language is pretty much as diverse as Python. It enables building cutting edge applications effortlessly. Developers are as yet investigating the full capability of end-to-end Python development services in various areas. 

By areas, we mean FinTech, HealthTech, InsureTech, Cybersecurity, and that's just the beginning. These are New Economy areas, and Python has the ability to serve every one of them. The vast majority of them require massive computational abilities. Python's code is dynamic and powerful - equipped for taking care of the heavy traffic and substantial algorithmic capacities. 

Programming advancement is multidimensional today. Endeavor programming requires an intelligent application with AI and ML capacities. Shopper based applications require information examination to convey a superior client experience. Netflix, Trello, and Amazon are genuine instances of such applications. Python assists with building them effortlessly. 

5 Reasons to Utilize Python for Programming Web Apps 

Python can do such numerous things that developers can't discover enough reasons to admire it. Python application development isn't restricted to web and enterprise applications. It is exceptionally adaptable and superb for a wide range of uses.

Robust frameworks 

Python is known for its tools and frameworks. There's a structure for everything. Django is helpful for building web applications, venture applications, logical applications, and mathematical processing. Flask is another web improvement framework with no conditions. 

Web2Py, CherryPy, and Falcon offer incredible capabilities to customize Python development services. A large portion of them are open-source frameworks that allow quick turn of events. 

Simple to read and compose 

Python has an improved sentence structure - one that is like the English language. New engineers for Python can undoubtedly understand where they stand in the development process. The simplicity of composing allows quick application building. 

The motivation behind building Python, as said by its maker Guido Van Rossum, was to empower even beginner engineers to comprehend the programming language. The simple coding likewise permits developers to roll out speedy improvements without getting confused by pointless subtleties. 

Utilized by the best 

Alright - Python isn't simply one more programming language. It should have something, which is the reason the business giants use it. Furthermore, that too for different purposes. Developers at Google use Python to assemble framework organization systems, parallel information pusher, code audit, testing and QA, and substantially more. Netflix utilizes Python web development services for its recommendation algorithm and media player. 

Massive community support 

Python has a steadily developing community that offers enormous help. From amateurs to specialists, there's everybody. There are a lot of instructional exercises, documentation, and guides accessible for Python web development solutions. 

Today, numerous universities start with Python, adding to the quantity of individuals in the community. Frequently, Python designers team up on various tasks and help each other with algorithmic, utilitarian, and application critical thinking. 

Progressive applications 

Python is the greatest supporter of data science, Machine Learning, and Artificial Intelligence at any enterprise software development company. Its utilization cases in cutting edge applications are the most compelling motivation for its prosperity. Python is the second most well known tool after R for data analytics.

The simplicity of getting sorted out, overseeing, and visualizing information through unique libraries makes it ideal for data based applications. TensorFlow for neural networks and OpenCV for computer vision are two of Python's most well known use cases for Machine learning applications.


Thinking about the advances in programming and innovation, Python is a YES for an assorted scope of utilizations. Game development, web application development services, GUI advancement, ML and AI improvement, Enterprise and customer applications - every one of them uses Python to its full potential. 

The disadvantages of Python web improvement arrangements are regularly disregarded by developers and organizations because of the advantages it gives. They focus on quality over speed and performance over blunders. That is the reason it's a good idea to utilize Python for building the applications of the future.

#python development services #python development company #python app development #python development #python in web development #python software development

Ray  Patel

Ray Patel


Common Anti-Patterns in Python

Improve and streamline your code by learning about these common anti-patterns that will save you time and effort. Examples of good and bad practices included.

1. Not Using with to Open Files

When you open a file without the with statement, you need to remember closing the file via calling close() explicitly when finished with processing it. Even while explicitly closing the resource, there are chances of exceptions before the resource is actually released. This can cause inconsistencies, or lead the file to be corrupted. Opening a file via with implements the context manager protocol that releases the resource when execution is outside of the with block.

2. Using list/dict/set Comprehension Unnecessarily

3. Unnecessary Use of Generators

4. Returning More Than One Object Type in a Function Call

5. Not Using get() to Return Default Values From a Dictionary

#code reviews #python programming #debugger #code review tips #python coding #python code #code debugging