Skip to content

Instantly share code, notes, and snippets.

@carlos-jenkins
Last active April 20, 2018 01:18
Show Gist options
  • Save carlos-jenkins/07f2c36ae987166d6c45d339191e6b97 to your computer and use it in GitHub Desktop.
Save carlos-jenkins/07f2c36ae987166d6c45d339191e6b97 to your computer and use it in GitHub Desktop.
Python format cheatsheet (PEP 3101 and PEP 3105)
# Python PEP 3101 specifies the string formatting function that
# replaces the old % operator on strings. In addition, PEP 3105
# also specifies the behavior of the print(), now standard in
# Python 3. This small cheat-sheet offer an overview of both.
# In Python 2.7 use with:
# from __future__ import print_function
# Print to stderr
>>> from sys import stderr
>>> print('ABC', file=stderr)
ABC
# Print without a newline
>>> print('ABC', end='')
ABC>>>
# Print multiple elements
>>> print('A', 'B', 'C', sep=', ')
A, B, C
# Print in hexadecimal
>>> print('0x{:X}'.format(15))
0xF
>>> print('0x{:08X}'.format(15))
0x0000000F
# Print in octal
>>> print('0o{:o}'.format(15))
0o17
>>> print('0o{:04o}'.format(15))
0o0017
# Print in binary
>>> print('0b{:b}'.format(15))
0b1111
>>> print('0b{:08b}'.format(15))
0b00001111
# Print decimal with leading zeros
>>> print('{:04d}'.format(15))
0015
# Print float with fixed precision
>>> print('{:.2f}'.format(15.0))
15.00
# Print with leading or trailing characters and alignment
>>> print('{:_>12}'.format('My String'))
___My String
>>> print('{:_<12}'.format('My String'))
My String___
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment