Skip to main content

String Format

The Python Variables chapter showed that a string and a number can't simply be added together:

f-strings and the format() method can both mix text and numbers, though!

Example

Prompt
Demonstrate Python string format.
Output: complete Python program

F-Strings

Python 3.6 brought in the f-string, which has since become the favoured tool for formatting text.

Making one is easy: write an f directly before the string literal, then use curly brackets {} to mark where variables and other operations should go.

Example

Prompt
Demonstrate Python f-strings.
Output: complete Python program

Placeholders and Modifiers

Inside a placeholder you can put a variable, an operation, a function, or a modifier that controls how the value is formatted.

Example

Prompt
Demonstrate Python placeholders and modifiers.
Output: complete Python program

Example

Prompt
Demonstrate Python placeholders and modifiers.
Output: complete Python program

Example

Prompt
Demonstrate Python placeholders and modifiers.
Output: complete Python program

Example

Prompt
Demonstrate Python placeholders and modifiers.
Output: complete Python program

Example

Prompt
Demonstrate Python placeholders and modifiers.
Output: complete Python program

Example

Prompt
Demonstrate Python placeholders and modifiers.
Output: complete Python program