---
jupytext:
  formats: content_md///md:myst,content///ipynb
  text_representation:
    extension: .md
    format_name: myst
    format_version: 0.13
    jupytext_version: 1.13.8
kernelspec:
  display_name: Python 3 (ipykernel)
  language: python
  name: python3
---

(python:strings:formatting)=
# String Formatting

## The `format` Method

String objects have a `format` method. This method allows for converting numbers and other data to strings.

```{code-cell} ipython3
a = 4
b = 5
c = a + b
nice_string = 'The result of {} plus {} is {}.'.format(a, b, c)
print(nice_string)
```

Calling the `format` method of a string replaces all pairs `{}` by the arguments passed to the format method. Next to integers also floats and strings can be passed to `format`. The original string is not modified because it's immutable. Instead, `format` returns a new string object.

The arguments of `format` can also be accessed by providing their index: the first argument has index 0, the second has index 1, and so on.

```{code-cell} ipython3
a = 4
b = a + a
print('The result of {0} plus {0} is {1}.'.format(a, b))
```

For more complex output (or more readable code) keyword arguments can be passed to format.

```{code-cell} ipython3
print('Mister {name} is {age} years old.'.format(name='Muller', age='42'))
```

Converting numbers to strings sometimes requires additional parameters: How many digits to use for floats? Shall numbers in several lines be aligned horizontally? There is a whole 'mini language' for writing formatting options. Here we provide only some examples. For details see [Python documentation on format string syntax](https://docs.python.org/3/library/string.html#formatstrings).

```{code-cell} ipython3
# print integer as float with 2 decimal places
print('The result is {:.2f}.'.format(3))

# right-align integers in fixed-width area
print('number of apples:  {:3d}'.format(2))
print('number of oranges: {:3d}'.format(145))

# same works for floats and strings
print('percentage of apples:  {:7.2f}'.format(2.1234))
print('percentage of oranges: {:7.2f}'.format(80.8976455))
print('percentage of bananas: {:7}'.format('unknown'))
```

If indices or names are used for refering to `format`’s arguments, they have to be placed on the left-hand side of the collon: `{name:3.2f}`.

## Formatted String Literals (f-Strings)

Starting with version 3.6 of Python there is a more comfortable way to format strings. It's very similar to formatting via `format` method, but requires less code and increases readability. The two major differences are:
* string literals have to be prefixed by `f`,
* the curly braces may contain a Python expression (an object name, for instance).

```{code-cell} ipython3
a = 123
print(f'Here you see {a}.')

b = 4.56789
print(f'Formatting works as above: {b:.2f} is a rounded float.')
```

For details see [formatted string literals](https://docs.python.org/3/tutorial/inputoutput.html?#formatted-string-literals) in the Python documentation.
