bugl
bugl
HomeLearnPatternsPathsSearch
HomeLearnPatternsPathsSearch

Loading lesson path

Learn/Python/Foundations
Python•Foundations

Python - Format - Strings

Flash cards

Review the key moves

1/4
Core idea

What is the main idea behind Python - Format - Strings?

Lesson checks

Practice each idea before moving on

Short Mimo-style checks built from this lesson's code, terms, and sequence.

1Quick choice

Which statement best captures the main point of this lesson?

2Fill blank

Complete the missing token from the example code.

#___ will produce an error:
3Order

Put the learning moves in the order that makes the concept easiest to apply.

F-String was introduced in Python 3.
But we can combine strings and numbers by using f-strings or the format() method!
Placeholders and Modifiers

String Format

As we learned in the Python Variables chapter, we cannot combine strings and numbers like this:

Example

age = 36
#This will produce an error:
  txt = "My name is John, I am " + age
  print(txt)

But we can combine strings and numbers by using f-strings or the format() method!

F-Strings

F-String was introduced in Python 3.6, and is now the preferred way of formatting strings.

To specify a string as an f-string, simply put an f in front of the string literal, and add curly brackets {} as placeholders for variables and other operations.

Example

age = 36
txt = f"My name is John, I am {age}"
print(txt)

Placeholders and Modifiers

A placeholder can contain variables, operations, functions, and modifiers to format the value.

price

A placeholder can include a modifier to format the value.

A modifier is included by adding a colon : followed by a legal formatting type, like .2f which means fixed point number with 2 decimals:

Example

price = 59

txt = f"The price is {price:.2f} dollars"

print(txt)

A placeholder can contain Python code, like math operations:

Example

txt = f"The price is {20 * 59} dollars"

print(txt)

Expected output

txt = f"The price is {20 * 59} dollars" print(txt)

Learn more about String Formatting in our String Formatting chapter.

Previous

Python - String Concatenation

Next

Python - Escape Characters