Title: String Formatting
Slug: string_formatting
Summary: String Formatting
Date: 2016-05-01 12:00
Category: Python
Tags: Basics
Authors: Chris Albon

Import the sys module


In [1]:
import sys

In [2]:
'This is %d %s bird!' % (1, 'dead')


Out[2]:
'This is 1 dead bird!'

In [3]:
'%(number)d more %(food)s' % {'number' : 1, 'food' : 'burger'}


Out[3]:
'1 more burger'

In [4]:
'My {1[kind]} runs {0.platform}'.format(sys, {'kind': 'laptop'})


Out[4]:
'My laptop runs darwin'

String Formatting Codes

  • %s string
  • %r repr string
  • %c character (integer or string)
  • %d decimal
  • %i integer
  • %x hex integer
  • %X same as X but with uppercase
  • %e floating point lowercase
  • %E floating point uppercase
  • %f floating point decimal lowercase
  • %F floating point decimal uppercase
  • %g floating point e or f
  • %G floating point E or F
  • %% literal %