Skip to content

Instantly share code, notes, and snippets.

@walterreade
Last active April 17, 2016 23:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save walterreade/0d1d33e4abbda04fa24a4503f73794cc to your computer and use it in GitHub Desktop.
Save walterreade/0d1d33e4abbda04fa24a4503f73794cc to your computer and use it in GitHub Desktop.
tag = 'h1'
text 'This is a headline'
sentence = '<{0}>{1}</{0}>'.format(tag, text)
person = {'name': 'Jenn', 'age': 23}
sentence = 'My name is {0[name]} and I am {0[age]} years old.'.format(person)
# can do the same for attributes, e.g., {0.name}, or list {0[0]}
# You can just unpack a dictionary!
sentence = 'My name is {name} and I am {age} years old.'.format(**person)
# : adds formatting
{:02} # pads two integers
{:.2f} # two decimal places
{:,} # adds comma separators for large values
{:,.2f} # you can chain formatting
import datetime
my_date datetime.datetime(2016, 9, 24, 12, 30, 45)
sentence = '{:%B %d, %Y}'.format(my_date)
# Padding - Strings
'{:>10}'.format('test') # Right
'{:10}'.format('test') # Left
'{:<{}s}'.format('test', 8) # Pass padding as argument
'{:_<10}'.format('test') # Choosing padding character
'{:^10}'.format('test') # Center align
'{:.5}'.format('xylophone') # Truncation
'{:.{}}'.format('xylophone', 7) # Truncation by argument
'{:10.5}'.format('xylophone') # Truncation and padding
# Numbers
'{:d}'.format(42) # Integers
'{:f}'.format(3.141592653589793) # Float
'{:4d}'.format(42) # Integer padding spaces
'{:04d}'.format(42) # Integer padding with zeros
'{:06.2f}'.format(3.141592653589793) # Float padding
'{:+d}'.format(42) # Signing positive numbers too
'{: d}'.format(42) # Format a negative, or a space for positive
# https://pyformat.info/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment