ruk·si

🐍 Python
Formatted String Literals

Updated at 2018-06-09 17:37

Always use formatted string literals. Avoid old styles like % and .format.

name: str = 'Ruksi'
assert f'{name!s}'    == "Ruksi"       # str()
assert f'{name!r}'    == "'Ruksi'"     # repr()
assert f'{name!a}'    == "'Ruksi'"     # ascii()

Padding.

name: str = 'Ruksi'
assert f'{name:>11}'  == '      Ruksi' # left padding
assert f'{name:<11}'  == 'Ruksi      ' # right padding
assert f'{name:^11}'  == '   Ruksi   ' # centering
assert f'{name:*^11}' == '***Ruksi***' # changing padding symbol

Rounding.

small: float = 1.23456789
assert f'{small:0.0f}' == '1'
assert f'{small:0.1f}' == '1.2'
assert f'{small:0.2f}' == '1.23'
assert f'{small:0.3f}' == '1.235'
assert f'{small:0.4f}' == '1.2346'

Thousand separator.

big: int = 123456789
assert f'{big:,}' == '123,456,789'     # thousand separator

Sign.

positive: float = 1.23
negative: float = -1.23
assert f'{positive} vs {negative}'       == '1.23 vs -1.23'
assert f'{positive: f} vs {negative: f}' == ' 1.230000 vs -1.230000'
assert f'{positive:+f} vs {negative:+f}' == '+1.230000 vs -1.230000'
assert f'{positive:-f} vs {negative:-f}' == '1.230000 vs -1.230000'

Source

  • Python Tricks The Book, Dan Bader
  • Fluent Python, Luciano Ramalho