CodeBlanks Logo Icon CodeBlanks

str.format

Learn formatting with str.format().

The str.format method

Before f-strings, str.format was used. You still see it in some code:

name = "Alex"
print("Hello {}".format(name))  # Hello Alex

{} is a placeholder; .format() fills them in order. Multiple placeholders are supported: "{} and {}".format("a", "b").

Modern code prefers f-strings; but knowing str.format is needed to read older code.

str.format vs f-string

Both methods do the same job, but f-strings are shorter:

# str.format
"Hello {}".format(name)

# f-string
f"Hello {name}"

f-strings are more readable and faster. Use f-strings in new code. Knowing str.format is enough for reading old code.

f-strings have been standard since Python 3.6 and are preferred in almost all modern code.

f-strings have been standard since Python 3.6 and are preferred in almost all modern code.

f-strings have been standard since Python 3.6 and are preferred in almost all modern code.

f-strings have been standard since Python 3.6 and are preferred in almost all modern code.

f-strings have been standard since Python 3.6 and are preferred in almost all modern code.

Practice Print str.format

Assign name = "Alex". Print print("Hello {}".format(name)).

Starter code

main.py
# Use str.format

Sample solution

main.py
name = "Alex"
print("Hello {}".format(name))

Expected output

Hello Alex

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does "{} and {}".format("a", "b") produce?

  • a and {}
  • {} and {}
  • a and b Correct answer
  • It raises an error

Explanation: .format() fills placeholders in order.

2 Write the placeholder

Question
print("Hello ____".format("Alex"))
Answer
print("Hello {}".format("Alex"))

Explanation: {} is the placeholder, filled by .format.

3 Match the methods

Term Meaning
f-string Modern method
str.format Older method
{} Placeholder
.format() Fill call

All lessons in Beginner