Monday, July 9, 2018

Format


Here is all you need to know about string formatting. I have summarized the page https://pyformat.info/ , in fact I just removed all explanations and made a simple cheat sheet in Jupyter Notebook. I copy the text here for convenience but you can download notebook file from GitHub


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

'{} {}'.format(1, 2)
Out[2]: '1 2'

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

class Data(object): 
     def __str__(self): 
          return 'str' 
     def __repr__(self): 
          return 'repr' 
'{0!s} {0!r}'.format(Data()) 

Out:'str repr'

class Data(object): 

     def __repr__(self): 
          return 'räpr' 
'{0!r} {0!a}'.format(Data())
Out: 
'räpr r\\xe4pr'

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

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

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

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

'{:.^6}'.format('zip')
Out:   '.zip..'

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

'{:.<10.5}'.format('xylophone')
Out:    'xylop.....'

'{:d}'.format(42)
Out:   '42'

'{:f}'.format(3.141592653589793)
Out:     '3.141593'

'>{:4d}<'.format(42)
Out:   '> 42<'

'{:06.2f}'.format(3.141592653589793)
Out:   '003.14'

'{:04d}'.format(42)
Out:   '0042'

'{:+d}'.format(42)
Out:    '+42'

'{: d}'.format(-23)
Out:    '-23'

'{: d}'.format(23)
Out:    ' 23'

'{:=5d}'.format(-23)
Out:    '- 23'

'{:=+5d}'.format(23)
Out:   '+ 23'

data = {'first': 'Hodor', 'last': 'Hodor!'} 
'{first} {last}'.format(**data)
Out:   'Hodor Hodor!'

'{first} {last}'.format(first='Hodor', last='Hodor!')
Out:   'Hodor Hodor!'

person = {'first': 'Jean-Luc', 'last': 'Picard'} '{p[first]} {p[last]}'.format(p=person)
Out:     'Jean-Luc Picard'

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

class Plant(object): type = 'tree' '{p.type}'.format(p=Plant())
Out:     'tree'

class Plant(object): 

        type = 'tree' 
kinds = [{'name': 'oak'}, {'name': 'maple'}] '{p.type}: {p.kinds[0][name]}'.format(p=Plant()) 
Out:  'tree: oak'

from datetime import datetime 

'{:%Y-%m-%d %H:%M}'.format(datetime(2001, 2, 3, 4, 5))
Out:   '2001-02-03 04:05'

'{:{align}{width}}'.format('test', align='^', width='10')
Out:    ' test '

'{:.{prec}} = {:.{prec}f}'.format('Gibberish', 2.7182, prec=3)
Out:     'Gib = 2.718'

'{:{width}.{prec}f}'.format(2.7182, width=5, prec=2)
Out:    ' 2.72'

'{:{prec}} = {:{prec}}'.format('Gibberish', 2.7182, prec='.3')
Out:    'Gib = 2.72'

from datetime import datetime 

dt = datetime(2001, 2, 3, 4, 5) 
'{:{dfmt} {tfmt}}'.format(dt, dfmt='%Y-%m-%d', tfmt='%H:%M')
Out:    '2001-02-03 04:05'

'{:{}{}{}.{}}'.format(2.7182818284, '>', '+', 10, 3)
Out:    ' +2.72'

'{:{}{sign}{}.{}}'.format(2.7182818284, '>', 10, 3, sign='+')
Out:    ' +2.72'

class HAL9000(object): 

       def __format__(self, format): 
                if (format == 'open-the-pod-bay-doors'): 
                         return "I'm afraid I can't do that." 
                return 'HAL 9000' 
'{:open-the-pod-bay-doors}'.format(HAL9000())
Out:    "I'm afraid I can't do that."

class data(object): 
     Height = 52 
     Weight = 75 
class food(object): 
        price = 12 
        stock = 200 
 'Height = {0.Height} and price = {1.price}'.format(data,food)
Out:    'Height = 52 and price = 12'

n=42 'Binary = {:b}'.format(n)
Out:     'Binary = 101010'

n=42 'Character = {:c}'.format(n)
Out:    'Character = *'

n=42 'Octal = {:o}'.format(n)
Out:     'Octal = 52'

n=42 'Value = {}'.format(n)
Out:     'Value = 42'

n=42 'Exponent = {:e}'.format(n)
Out:    'Exponent = 4.200000e+01'

n=42 'Fixed Point = {:f}'.format(n)
Out:    'Fixed Point = 42.000000'

n=42 'Fixed Point = {:%}'.format(n)
Out:   'Fixed Point = 4200.000000%'


Twitter: @DataScienceStep

No comments:

Post a Comment

Format

Here is all you need to know about string formatting. I have summarized the page  https://pyformat.info/  , in fact I just removed all e...