Skip to content

Format

print

To print without new line in python3

>>> print('Print without newline', end='')
Print without newline>>>

In python2:

print print without newline,

format

https://pyformat.info/

Basic formatting:

'{} {}'.format('one', 'two')
'one two'

'{1} {0}'.format('one', 'two')
'two one'

Padding and aligning strings

Align Right:

'{:>10}'.format('test')
'    test'

'{:->10}'.format('test')
'----test'

Align Left

'{:10}'.format('test')
'test    '

'{:-<10}'.format('test')
'test----'

Align Center

'{:^10}'.format('test')
'   test   '

'{:-^10}'.format('test')
'---test---'

Truncating long strings

'{:.5}'.format('xylophone')
'xylop'

Numbers and conversions using format

Padding numbers:
'{:4d}'.format(42)
'  42'

format decimal to binary
{:b}.format(255))   
'11111111'

format decimal to octal
{:o}.format(255)) 
'377'

To format decimal to Hexadecimal
'{:X}'.format(255) 
'FF'

octal and rjust with 8 character width
'{:8o}'.format(255)
'     377'

'{:<8o}'.format(255)
'377     '

'{0} {0} {0} {0}'.format(15)
'15 15 15 15'

'{0:5d} {0:5X} {0:5b} {0:5o}'.format(15)
'   15    F  1111   17'

'{0:{w}d} {0:{w}X} {0:{w}b} {0:{w}o}'.format(15, w=5)
'   15    F  1111   17'

Floating points:

'{:.54}'.format(15)
'15.0000'

'{:.5f}'.format(3.14234342)
'3.14234'

Named placeholders

data = {'first': 'Hodor', 'last': 'Hodor!'}

'{first} {last}'.format(**data)
'Hodor Hodor!'
Getitem and Getattr New style formatting allows even greater flexibility in accessing nested data structures.

person = {'first':'jeeva', 'last':'kailasam'}
'{p[first]} {p[last]}'.format(p=person)
'jeeva kailasam'

data = [4, 8, 15, 16, 23, 42]
'{d[4]} {d[5]}'.format(d=data)
'23 42'