Zum Inhalt

String formatting

There are different ways to format strings in python. The modern way are the f-strings.

Using f-strings

name='John'
print(f'Hello {name}')

# older, less readable version
print('Hello %s' % name)

You can also format datetime and float directly using f-strings like with .format:

from datetime import datetime

now = datetime.utcnow()

text = f"Today's date: {now:%d.%m.%Y}"
print(text)
price = 1.257

# Round to one decimal place after the comma
text = f'the price is {price:.1f}'
print(text)

But what if you need {} in your text template? You can add additional brackets, but in doubles:

event = 'wake_up'
out = f'on: {{ {event} }}'
assert out == 'on: { wake_up }'

You need to combine that with regex? The following is an example would be an example of building a regex with rf'...' for different file endings.

import re
endings = ('yaml', 'json')
patt = re.compile(rf'[\w_]+\.({"|".join(endings)})')
m =patt.search('hello_world.json')
print(m)

Builtin str.format

This method is very handy if you want to give your template variables names. Let's consider the following example where you set URL's that are templates later in the process.

import requests

class Api:
    base_url = 'https://my-api.org'
    user_url = '/user/{user_id}'

    def get_user(self, user_id: str, **kwargs):
        # .format is not raising error for keyword arguments that are not in the string
        # it is forgiving in that sense
        return self._get(self.user_url.format(user_id=user_id, **kwargs))

    def _get(self, url: str):
        return requests.get(f'{self.base_url}{url}')

Letztes Update: March 25, 2023
Erstellt: June 27, 2022