How to Use f-strings in Python for String Formatting

40.9K views
•
April 25, 2023
by
Neso Academy
YouTube video player
How to Use f-strings in Python for String Formatting

TL;DR

f-strings format a string by prefixing it with the letter f and placing objects inside curly braces, like f"my name is {name}". At runtime, {name} is replaced by the variable's value. You can call methods such as .upper() inside the braces, spread f-strings across multiple lines, and use single, double, or triple quotes.

Transcript

foreign let's continue our discussion on string formatting this is part two of string formatting in this presentation we will discuss only one topic let's see the topic the topic that we will understand is f strings so without any further delay let's get started and let's understand what is F string F string is used to format a string so with the h... Read More

Key Insights

  • An f-string is created by typing the letter f before a quoted string, then placing any external object inside curly braces; at runtime the object is replaced by the value it points to, for example f"my name is {name}" yields "my name is jaspreet".
  • Both lowercase f and uppercase F work identically as the f-string prefix, and the string itself can be wrapped in single quotes or double quotes with no restriction on which you use.
  • String methods can be called directly inside the curly braces; f"my name is {name.upper()}" calls the upper method on the string the variable points to, capitalizing every letter to produce "JUSPREET".
  • Multi-line f-strings improve readability and can be written by ending each line with a backslash, so three separate f-string lines join into a single output line when the variable is printed.
  • Wrapping multiple f-strings in round brackets is an alternative to backslashes for spreading an f-string across several lines, producing the same combined single-line result.
  • Triple quotes let you write multi-line f-strings, but unlike backslashes and round brackets they preserve new lines, tabs, and white spaces, so escape characters like backslash n and backslash t appear in the output.
  • Any type of quotation mark is allowed, but if the outer f-string uses double quotes the inner object must use single quotes, and if the outer uses single quotes the inner must use double quotes; Python always displays its result in single quotes.
  • A backslash placed in front of a quotation mark escapes it, allowing quote characters to appear inside the string instead of triggering a syntax error such as "invalid syntax".

Install to Summarize YouTube Videos and Get Transcripts

Explore YouTube Video Summarizer or Get YouTube Transcript Extractor

Questions & Answers

Q: How do you create an f-string in Python?

You create an f-string by typing the letter f first, then a string inside double or single quotes, and placing any external object inside curly braces. For example, after setting name = 'just breathe' and city = 'Delhi', writing f"my name is {name} and I live in {city}" produces "my name is jaspreet and I live in Delhi". The curly-brace objects are replaced by the values the variables point to at runtime.

Q: What is an f-string used for?

An f-string is used to format a string. With this technique you can embed external objects, such as variables, directly inside a string by placing them within curly braces. The syntax requires typing f first, then the string within quotes, and any object of your choice inside the braces. At runtime the object is replaced by the string or value it points to, giving you a single formatted result string.

Q: Can you call a string method inside an f-string?

Yes, calling a method of a string is possible within an f-string. For example, f"my name is {name.upper()} and I live in {city.upper()}" calls the upper method, which capitalizes each letter of the string. Since the variable points to a string, you are effectively calling the upper method on that string, producing an output where every letter of the included strings appears in uppercase.

Q: How do you write a multi-line f-string in Python?

There are three ways to spread an f-string across multiple lines. First, end each line with a backslash after the closing quote to continue onto the next line. Second, wrap all the f-string pieces inside round brackets. Third, use triple quotes with a single f prefix. All produce a combined result, but the goal is multi-line f-strings written for readability, not multi-line strings in the output itself.

Q: Why do triple-quoted f-strings show backslash n and backslash t in the output?

Triple quotes preserve new lines, tabs, and white spaces. When you write a multi-line f-string using triple quotes and indent lines with tabs or add new lines for readability, those characters are kept. That is why the output shows backslash n for the new line and backslash t for each tab you added. Backslashes and round brackets do not preserve these characters, but triple quotes do.

Q: What quotation marks can you use in an f-string?

You can use any type of quotation marks in an f-string: single, double, or triple quotes. However, if the outer f-string uses double quotes, then any inner string must use single quotes, and if the outer uses single quotes, the inner must use double quotes. Both regular triple quotes and single triple quotes are also allowed. Python always displays its resulting string in single quotes regardless of which you use.

Q: How do you include a quotation mark inside an f-string?

You use a backslash to escape the quotation marks. If you try to place double quotes directly inside a double-quoted string, Python raises a syntax error saying invalid syntax, because those inner double quotes are not allowed. Adding a backslash in front of each inner quotation mark escapes it, so the quote character becomes part of the string instead of ending it, for example writing backslash before the double quote.

Q: Does the f prefix have to be lowercase in an f-string?

No, the f prefix does not have to be lowercase. In place of a small f you are allowed to use a capital F, and both work identically. For example, F"my name is {name} and I live in {city}" produces the same result as the lowercase version, giving "my name is jaspreet and I live in Delhi". Similarly, you can choose either single or double quotes with no restriction on which quote type you use.

Summary & Key Takeaways

  • An f-string formats a string by prefixing it with f or F and enclosing variables or objects in curly braces. Typing f"my name is {name} and I live in {city}" replaces name with "just breathe" and city with "Delhi" at runtime, producing the fully formatted output string.

  • You can call a string method inside the braces, such as {name.upper()}, which capitalizes each letter. f-strings can also be spread across multiple lines for readability using a trailing backslash, by wrapping the pieces in round brackets, or by using triple quotes, though triple quotes preserve newlines, tabs, and spaces.

  • Any quotation marks are allowed, but outer and inner quotes must differ: double outside requires single inside and vice versa. Python always shows results in single quotes. A backslash escapes a quotation mark inside the string, preventing the invalid-syntax error that unescaped inner double quotes would cause.


Read in Other Languages (beta)

Share This Summary 📚

Summarize YouTube Videos and Get Video Transcripts with 1-Click

Download browser extensions on:

Try YouTube Summary with ChatGPT & Claude or YouTube Transcript Generator

Explore More Summaries from Neso Academy 📚

Summarize YouTube Videos and Get Video Transcripts with 1-Click

Download browser extensions on:

Try YouTube Summary with ChatGPT & Claude or YouTube Transcript Generator