Skip to content

Instantly share code, notes, and snippets.

@Integralist
Last active November 22, 2018 11:27
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 Integralist/31bd757258a956d49c0504b36903e2d7 to your computer and use it in GitHub Desktop.
Save Integralist/31bd757258a956d49c0504b36903e2d7 to your computer and use it in GitHub Desktop.
[Python String Formatting] #python #string #formatting

f-string

f'approx pi: {math.pi:.3f}'  # 'approx pi: 3.142'
f'approx pi: {math.pi:.10f}'  # 'approx pi: 3.1415926536'

# padding...
foo = 'bar'
baz = 'qux'

f'{foo:10}'  # 'bar       '
f'{foo:10} => {baz}'  # 'bar        => qux'

string .format()

'{}'.format('foo')  # 'foo'
'{1}'.format('foo', 'bar')  # 'bar'
'{foo} {baz}'.format(foo='bar', baz='qux')  # 'bar qux'
'{0[foo]} {0[baz]}'.format({'foo': 'bar', 'baz': 'qux'})  # 'bar qux'
'{0[foo]:f} {0[baz]:f}'.format({'foo': 1.23, 'baz': 4.5})  # '1.230000 4.500000'

Note: in last example, if you would use the type to trigger an exception if the input didn't match: '{0[foo]:f} {0[baz]:d}'.format({'foo': 1.23, 'baz': 4.5}) would raise a ValueError: Unknown format code 'd' for object of type 'float'.

traditional sprintf

'foo%s' % 'bar'  # foobar
'foo%(bar)s' % {'foo': 'FOO', 'bar': 'BAR'}  # fooBAR
'num: %f' % 1.2  # 'num: 1.200000'
'pi: %5.3f' % math.pi  # 'pi: 3.142'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment