Skip to content

Instantly share code, notes, and snippets.

@corei8
Created March 19, 2024 18:03
Show Gist options
  • Save corei8/2083b3ff08631c0120b7a1404db01bf9 to your computer and use it in GitHub Desktop.
Save corei8/2083b3ff08631c0120b7a1404db01bf9 to your computer and use it in GitHub Desktop.
F-string examples from Indently on YouTube
# scientific notion with number of decimals after period
big_number: int = 1_620_000_000
print(f'{big_number:.2e}')
# format dates on the fly
from datetime import datetime
now: datetime = datetime.now()
print(f'{now:%d.%m.%y}')
# nesting f-strings
number: float = 1000000.1234567
spec: str = ',.2f'
print(f'{number:{spec}')
# r before a string escapes escape characters, and this can be used in tandem with f-strings
print(rf'{}')
# debug with f-strings
a: float = 0.1
b: float = 0.2
print(f'{a + b = :.1f}')
#
from datatime import datetime, date
banana: str = '🍌'
name: str = 'Bob'
today: date = datetime.now().date()
print(f'[{today!s}] {name!s} says: {banana!s}') # string representation per variable
print(f'[{today!r}] {name!r} says: {banana!r}') # representation of each variable
print(f'[{today!a}] {name!a} says: {banana!a}') # ASCII representation of each variable
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment