Python f-String Tutorial – String Formatting in Python Explained with Code Examples (2024)

/ #Python
Python f-String Tutorial – String Formatting in Python Explained with Code Examples (1)
Bala Priya C
Python f-String Tutorial – String Formatting in Python Explained with Code Examples (2)

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:

#OutputI'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 = 83num2 = 9print(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.

#OutputThe 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>else: # 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.
#OutputIs 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}.")#OutputThis 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.

#OutputThis 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!" else: 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:

#OutputHello 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)}")
#OutputHello Python, tell me what I should learn. Learn Python!

And that ends our tutorial on a happy note!

Conclusion

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.

Related Posts

Here's a post by Jessica that explains string formatting using the format() method.

ADVERTIsem*nT

ADVERTIsem*nT

ADVERTIsem*nT

ADVERTIsem*nT

ADVERTIsem*nT

ADVERTIsem*nT

ADVERTIsem*nT

Python f-String Tutorial – String Formatting in Python Explained with Code Examples (3)
Bala Priya C

I am a developer and technical writer from India. I write tutorials on all things programming and machine learning.

If you read this far, thank the author to show them you care.

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

ADVERTIsem*nT

Python f-String Tutorial – String Formatting in Python Explained with Code Examples (2024)

FAQs

What is f-string in Python with example? ›

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. sentence = f"My name is {name} and I am {age} years old."

How do you print a string in Python F format? ›

To use formatted string literals, begin a string with f or F before the opening quotation mark or triple quotation mark in a print() statement. Inside this string, you can write a Python expression between { } characters that can refer to variables or literal values.

How to escape {} in Python f-string? ›

To escape curly braces in an f-string, you need to double the curly braces. This tells Python to treat the curly braces as literal characters rather than as part of the expression. Here's an example: name = "Alice" age = 25 print(f"My name is {{name}} and I am {{age}} years old.")

What is the best way of string formatting in Python? ›

Formatting Strings Using the Formatted String Literals (f)

The formatted string literals which was introduced in Python 3 is the latest and most straightforward way of formatting strings in Python. We put the letter f or F in front of a string literal and specify expressions within curly braces {} in the string.

When should I use F-string 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 is a string explain with examples in Python? ›

In Python, a string is a sequence of characters. For example, "hello" is a string containing a sequence of characters 'h' , 'e' , 'l' , 'l' , and 'o' .

How to beautify Python code? ›

Open a Python file. Right-click anywhere in the file and select 'Format Document' from the context menu. VS Code will automatically format the document using the default formatter. You can also configure a specific formatter like black or autopep8 in the settings.

How to format text in Python? ›

To provide some context to this post: Python has three different approaches for string formatting:
  1. printf-style percent formatting. formatted = "ssh %s@%s" % (username, hostname)
  2. str.format() calls: formatted = "ssh {0}@{1}".format(username, hostname)
  3. f-strings: formatted = f"ssh {username}@{hostname}"
Jun 23, 2020

How do you convert to string format in Python? ›

There are several methods for converting an integer into a string, we can use typecasting (str() function), %s keyword, . format() function and f-strings method. While using the . format() function and f-strings method, we can also format the representation of values while converting the value into a string.

What is the literal in Python F-string? ›

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 to print brackets in Python f-string? ›

To print a curly brace character in a string while using the . format() method in Python, you can use double curly braces {{ and }} to escape the curly braces.

What is the double quote in Python F? ›

🔹 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 can you round down a number when you use 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.

What is a format example? ›

Examples of format in a Sentence

Noun The journals are available in electronic format. The file is saved in MP3 format. Verb The book is formatted in several different styles. The data was improperly formatted.

What is the fastest string formatting in Python? ›

f-strings are the fastest way of formatting a string.

What does F mean in a string? ›

String starting with f are formatted string literals. Suppose you have a variable: pi = 3.14. To concatenate it to a string you'd do: s = "pi = " + str(pi)

What is the format of .2f string? ›

The format specifier . 2f states that we want to display 2 decimals. The letter f at the end means that we want the variable to be displayed as a float , i.e. a floating point number. You can think of an f-string as a sort of function, which creates a normal string based on the "arguments" within the curly brackets.

What is the F-string error in Python? ›

What Causes IndexError: string index out of range. This error occurs when an attempt is made to access a character in a string at an index that does not exist in the string. The range of a string in Python is [0, len(str) - 1] , where len(str) is the length of the string.

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.

References

Top Articles
The BEST Gluten-Free Rolls Recipe
Best Taco Seasoning Recipe - Kristine's Kitchen
12 Rue Gotlib 21St Arrondissem*nt
Gilbert Public Schools Infinite Campus
Bon plan – Le smartphone Motorola Edge 50 Fusion "4 étoiles" à 339,99 €
Ofw Pinoy Channel Su
Savage X Fenty Wiki
Promiseb Discontinued
123Movies The Idol
Craigslist Pets Longview Tx
Missed Connections Dayton Ohio
manhattan cars & trucks - by owner - craigslist
Westelm Order
The Nun 2 Showtimes Tinseltown
Knock At The Cabin Showtimes Near Fat Cats Mesa
8 Garden Sprayers That Work Hard So You Don't Have To
Babylon Alligator
Join MileSplit to get access to the latest news, films, and events!
Fintechzoommortgagecalculator.live Hours
Cbs Local News Sacramento
Fingerfang Rock Conan
JPMorgan and 6 More Companies That Are Hiring in 2024, Defying the Layoffs Trend
352-730-1982
Oppenheimer Showtimes Near Amc Rivertowne 12
Solid Red Light Litter Robot 4
Guide:How to make WvW Legendary Armor
Milf Lingerie Caption
Danielle Moodie-Mills Net Worth
Jvid Rina Sauce
Cronología De Chelsea Contra Fulham
Tqha Yearling Sale 2023 Results
Bolly2Tolly Sale
Craigslist Cars Los Angeles
Kltv Com Big Red Box
Katie Sigmond - Net Worth 2022, Age, Height, Bio, Family, Career
Ralph Macchio Conservative
How To Use Price Chopper Points At Quiktrip
Vernon Autoplex
How To Create A Top Uber Boss Killer In POE 3.25 League?
The Legend of Maula Jatt | Rotten Tomatoes
Below Her Mouth | Rotten Tomatoes
Recharging Iban Staff
Franchisee Training & Support | Papa Johns Pizza Franchise UK
Pressconnects Obituaries Recent
Saw X Showtimes Near Stone Theatres Sun Valley 14 Cinemas
Leuke tips & bezienswaardigheden voor een dagje Wijk bij Duurstede
Plusword 358
Lifetime Benefits Login
Craigslist Pelham Al
Alvin Isd Ixl
The t33n leak 5-17: Understanding the Impact and Implications - Mole Removal Service
Nfl Spotrac Transactions
Latest Posts
Article information

Author: Sen. Ignacio Ratke

Last Updated:

Views: 5903

Rating: 4.6 / 5 (56 voted)

Reviews: 95% 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.