HOLIDAY SALE! Save 50% on Membership with code HOLIDAY50. Save 15% on Mentorship with code HOLIDAY15.

11) User Input and String Formatting Lesson

String Formatting in Python

6 min to complete · By Martin Breuss

If you're handling a lot of string output to communicate information from your program to users, then concatenating long string messages can quickly get messy.

Python 3.6 introduced a new version of string formatting called f-strings that makes this task more enjoyable.

Python F String

Using f-strings, you can format your strings with a concise and very readable syntax that embeds any Python expressions right into your string:

name = "Tom"
age = 99

print(f"Hello {name}. Next year you'll be {age + 1}!")

F String Format

  1. f: To let Python know that you want a string to be an f-string, you need to add the letter f, or F, in front of the opening quotes.
  2. {}: To inject the value of a variable, or the result of an expression, into your f-string, you need to wrap the code into curly braces ({}).

As you can see from the example above, this syntax allows you not only to add variables directly into the string but also to do all sorts of calculations right in between the curly braces.

As long as the code you add in there is an expression, you can make it directly part of your f-string.

Colorful illustration of a light bulb

Info: An expression is any combination of programming logic that evaluates to a result. For example, adding two numbers together is an expression because it results in the sum of the two numbers.

F-String Example

With the f-string syntax, you can create strings in an intuitive way:

print("Welcome to the unfulfilling market!")
print("Tell us what you want, and we won't have it.")

food = input("What do you want? ")
amount = int(input(f"How much of {food}? "))

print(f"You want {amount} {food}? Sorry, we only have {amount - 1}.")

In this example, the vendor in the unfulfilling market asks the customer what they want and how much of it. Then, they proceed to tell the customer that they don't have enough of it.

You can see that you're using two f-strings in this example, which makes writing the communication strings more intuitive for you.

Str.format Python

If you are working with versions of Python that are older than 3.6, you can use str.format() to format your strings. It provides a similar syntax:

name = "Tom"
age = 99

print(f"Hello {}. Next year you'll be {}!".format(name, age + 1))

F String vs Str.format

The advantage of using f-strings over str.format() is that f-strings are better readable, especially in long strings that include many variables.

You can also pass an index to the curly braces ({}) in str.format():

print("{0} is not {1}, but it's {0}!".format("Basil", "Sage"))

Using index numbers allows you to reuse arguments in multiple places in your string. It also makes it possible to mix up the order in which the arguments get inserted into the string.

Practice with Str.format

  • Flip the above statement about spices only by changing the index numbers inside the curly braces ({}).
  • Rewrite the unfulfilling market vendor code snippet using str.format() instead of f-strings.

Python includes even more different ways to format your strings. However, unless you have a specific reason for it, you should stick with using f-strings.

Colorful illustration of a light bulb

Additional Resources

Summary: String Formatting in Python

  • F strings are a practical way to format your strings
  • F strings are created by putting an f or F before the starting quotation of your string
  • F strings allow you to insert variables and expressions right into your strings with curly braces {}
  • This syntax makes f-strings intuitive to read and very flexible
  • str.format is another way to format strings in Python
  • Functionality is the same, but it is harder to read and requires more code