Tuesday, 5 September 2017

Python format

Old '%s %s' % ('one', 'two')

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

Old '%d %d' % (1, 2)

New '{} {}'.format(1, 2)


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

Output two one

Padding and aligning strings



Align right:

Old '%10s' % ('test',)

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

Output         test

Align left:

Old '%-10s' % ('test',)

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

Output test     

And also center align values:

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

Output        test    

Padding numbers

Old '%4d' % (42,)

New '{:4d}'.format(42)

Output 42

Old '%06.2f' % (3.141592653589793,)

New '{:06.2f}'.format(3.141592653589793)

Output 003.14

No comments:

Post a Comment