p

python tutorial - Formatting dictionary strings - learn python - python programming



  • Targets on the left can refer to the keys in a dictionary on the right so that they can fetch the corresponding values.
  • In the example below, the (m) and (w) in the format string refers to the keys in the dictionary on the right and fetch their corresponding values.
  • We can build a dictionary of values and substitute them all at once with a single formatting expression that uses key-based references. This technique can be used to generate text:
>>> greetings = '''
Hello %(name)s!
Merry Christmas.
I hope %(year)d will be a good year.
'''
>>> replace = {'name' : 'Scala', 'year' : 2013}
>>> print(greetings % replace)

Hello Scala!
Merry Christmas.
I hope 2017 will be a good year.
click below button to copy the code. By Python tutorial team
  • As an another example, we can use it for build-in function, vars():
>>> language = 'Python'
>>> version = 320
>>> vars()
{'language': 'Python', '__builtins__': , 
'__package__': None, 'version': 320, '__name__': '__main__', '__doc__': None}
>>> '%(language)s %(version)d' % vars()
'Python 320'
click below button to copy the code. By Python tutorial team

String formatting by method calls

  • Unlike formatting using expressions which is based on C's printf, string formatting using method calls is regarded as more Python-specific.

Template basics

  • This new string object's format method uses the subject string as a template and takes any number of arguments that represent values to the substituted according to the template.
  • Within the subject string, curly braces designate substitution targets and arguments to be inserted either by position such as {1} or keyword such as language.
>>> # By position
>>> t = '{0}, {1}, {2}'
>>> t.format('Dec', '29', '2013')
'Dec, 29, 2013'
>>>
>>> # By keyword
>>> t = '{Month}, {Day}, {Year}'
>>> t.format(Month='Dec', Day='29', Year='2013')
'Dec, 29, 2013'
>>>
>>> # Mixed
>>> t = '{Year}, {Month}, {0}'
>>> t
'{Year}, {Month}, {0}'
>>> t.format('29', Year='2013', Month='Dec')
'2013, Dec, 29'
>>> 
click below button to copy the code. By Python tutorial team
  • Arbitrary object type can be substituted from a temporary string:
>>> '{Month}, {Year}, {0}'.format('29', Month=['Nov', 'Dec'], Year='2013')	  
"['Nov', 'Dec'], 2017, 29"
click below button to copy the code. By Python tutorial team

Formatting with keys and attributes

  • Format strings can name object attributes and dictionary keys.
  • Square brackets name dictionary keys and dots denote object attributes of an item referenced by position or keyword.
>>> import sys
>>>
>>> 'My {0[Machine]} is running {1.platform}'.format({'Machine': 'notebook'}, sys)
'My notebook is running win32'
>>>
>>> 'My {config[Machine]} is running {sys.platform}'.format(config={'Machine':'notebook'}, sys=sys)
'My notebook is running win32'
click below button to copy the code. By Python tutorial team
  • In the example above, the first one indexes a dictionary on the key Machine and then fetches the attribute platform from the imported sys module.
  • Though the 2nd case in the example is doing the same thing, but names the objects by keyword not by its position.

Working with specific formatting

  • By adding extra syntax in the format string, we can achieve more specific layouts similar to the % expressions.
{fieldName!conversionFlag:formatSpecification}
click below button to copy the code. By Python tutorial team
  • For the formatting method, we can use a colon after the substitution target's identification, followed by a format specifier that can name the field size, justification, and a specific type code.
    • fieldName is a number or keyword naming an argument, followed by optional .name attribute or [index] references.
    • conversionFlag can be r, s, or a to call repr, str, or ascii built-in functions on the value, respectively.
    • formatSpecification specifies how the value should be presented.
  • The alignment for the formatSpecification can be <. >, =, or ^, for left alignment, right alignment, padding after a sign character, or centered alignment, respectively.
>>> '{0:10} = {1:5}'.format(3.1415, 'pi')
'    3.1415 = pi   '
>>> '{0:15} = {1:10}'.format(3.1415, 'pi')
'         3.1415 = pi        '
>>> '{0:<15} = {1:>10}'.format(3.1415, 'pi')
'3.1415          =         pi'
>>>
>>> '{0.platform:>10} is the platform of my {1[item]:<10}'.format(sys, dict(item='notebook'))
'     win32 is the platform of my notebook  '
>>> 
click below button to copy the code. By Python tutorial team
  • The following example shows the specification for floating point numbers:
>>> '{0:e},{1:3e},{2:g},{3:f},{4:.2f},{5:06.2f}'.format(3.1415,3.1415,3.1415,3.1415,3.1415,3.1415)
'3.141500e+00,3.141500e+00,3.1415,3.141500,3.14,003.14'
>>> 
click below button to copy the code. By Python tutorial team
  • The following example is for the review of formatting we've discussed so far:
# byte.py
UNITS = ['KB', 'MB', 'GB', 'TB', 'PB']

def sizeInByte(sz):
    if sz < 0:
        raise ValueError('number < 0')

    factor = 1024 
    for i in range(len(UNITS)):
        if sz < factor:
            if i == 0:
                return '{0:.1f} {1[0]}'.format(sz, UNITS)
            elif i == 1:
                return '{0:.1f} {1[1]}'.format(sz, UNITS)
            elif i == 2:
                return '{0:.1f} {1[2]}'.format(sz, UNITS)
            elif i == 3:
                return '{0:.1f} {1[3]}'.format(sz, UNITS)
            else:
                return '{0:.1f} {1[4]}'.format(sz, UNITS)
        else:
            sz /= factor

    raise ValueError('too big')
click below button to copy the code. By Python tutorial team
  • After importing the module, we get the following output from the interactive shell:
>>> from byte import sizeInByte
>>> sizeInByte(10000)
'9.8 MB'
>>> sizeInByte(100000000)
'95.4 GB'
>>> sizeInByte(10000000000000)
'9.1 PB'
>>> sizeInByte(1000000000000000000000)
Traceback (most recent call last):
  File "", line 1, in 
  File "byte.py", line 23, in sizeInByte
    raise ValueError('too big')
ValueError: too big
>>>
click below button to copy the code. By Python tutorial team
  • The first specification {0:.1f} is for the sz and the second one {1[0]} is for the 'KB' in UNITS list.

Related Searches to Formatting dictionary strings