Skip to content

Instantly share code, notes, and snippets.

@terremoth
Created April 27, 2024 03:15
Show Gist options
  • Save terremoth/9f39d7cc5c9b248c4d12105e9f6c36f4 to your computer and use it in GitHub Desktop.
Save terremoth/9f39d7cc5c9b248c4d12105e9f6c36f4 to your computer and use it in GitHub Desktop.
Python string formatting tricks
number: int = 1_000_000_000
print(number) # 1000000000
print(f'{number:_}') # 1_000_000_000
print(f'{number:,}') # 1,000,000,000
var: str = 'var'
print(f'{var:>20}')
print(f'ooooh{var:>20}')
print(f'{var:<20}')
print(f'{var:<20}:')
print(f'{var:<20}:ABCD')
print(f'{var:^20}:ABCD')
print(f'{var:#<20}:ABCD')
from datetime import datetime as dt
now: dt = dt.now()
print(f'{now:%d/%m/%Y}')
print(f'{now:%c}')
print(f'{now:%I%p}')
float_num: float = 1234.5678
print(f'{float_num:.2f}')
print(f'{float_num:.0f}')
print(f'{float_num:,.2f}')
print(f'{float_num:_.2f}')
a_num: int = 5
b_num: int = 10
my_var: str = 'Lucas says hi!'
print(f'{a_num + b_num =}')
print(f'{my_var = }')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment