## What
f-strings are a convenient way to format [[string|strings]] in Python. You can do a lot of useful things with f-strings so should read the [official Python documentation](https://docs.python.org/3/reference/lexical_analysis.html#f-strings) or this [f-string cheat sheet](https://fstring.help/) for more detail.
## Syntax
An f-string is a string literal prefixed with `f`, e.g., `f"hello {name}"`. Any expression inside `{}` is evaluated and inserted into the string—this works for variables, subprogram calls, or any other expression that returns a value.
A `:` after the expression allows for additional formatting, controlling how the value is displayed—e.g., `{pi:.2f}` formats `pi` to 2 decimal places.
## Why
f-strings allow the composition of strings using different data types without the need for [[casting]] and support lots of clever formatting options (e.g., decimal places, padding).
f-strings are almost always a better choice than passing multiple [[argument|arguments]] to `print()`, and are almost always a better choice than using [[concatenate|concatenation]]—f-strings are easy for humans to read.
> [!WARNING] f-string != concatenation
> f-strings are not a substitute for [[concatenate|concatenation]]—they work in fundamentally different ways. If you are instructed to use concatenation in an exam question, you will not get the mark if you use an f-string.
## Examples
### Combining strings
The simplest use of an f-string: inserting variable values directly into a string—has the same visible result of concatenation, but is achieved differently.
```python
forename = "Richard"
surname = "Tape"
fullname = f"{forename} {surname}" # "Richard Tape"
greeting = f"Hello {fullname}" # "Hello Richard Tape"
```
### Mixing data types
f-strings handle different data types without needing to cast them to strings first.
```python
height = 1.75
age = 18
name = "Clytemnestra"
message = f"{name} is {height}m tall and {age} years old"
# "Clytemnestra is 1.75m tall and 18 years old"
```
### Mixing data types and string operations
The expression inside `{}` isn't limited to just variables—it can include subprogram calls and indexing.
```python
forename = "Ophelia"
surname = "Baggins"
class_year = 22
username = f"{class_year}{forename[0].lower()}{surname.lower()}"
# "22obaggins"
```
### Formatting numbers
The format spec after `:` controls how the value is displayed and does not change the underlying value. See the [official Python documentation](https://docs.python.org/3/reference/lexical_analysis.html#f-strings) or this [f-string cheat sheet](https://fstring.help/) for more options.
```python
pi = 3.14159
message = f"pi to 2 decimal places is {pi:.2f}"
# "pi to 2 decimal places is 3.14"
# pi still equals 3.14159
```