Search code examples
pythonstring-formatting

How to reference the empty string key in the Format String Syntax?


The empty string ('') is a pertectly valid key for a dictionary, but I can not reference it using the Format String Syntax

data = { 'a' : 'hello' , '' : 'bye' }
print '{a:<14s}'.format(**data)
print '{:<14s}'.format(**data)

Which outputs:

hello         
Traceback (most recent call last):
  File "xxx.py", line 3, in <module>
    print '{:<14s}'.format(**data)
IndexError: tuple index out of range

Is there any way of referencing that key ... as a dictionary key! I can not convert the data to tuples; a bit of background: I am doing some auto-formatting based on a generic format spec which gets converted to Format String Syntax using dicts as data for the formatting. That is, I can not do this:

print '{0:<14s}'.format(data[''])

The data must always be passed to format as **data (basically, because I am doing a generic .format(**data) in my formatter class)


Solution

  • You can't use an empty string. The format strictly limits keys to valid Python identifiers, which means they have to have at least 1 letter or underscore at the start.

    From the grammar in the Format String Syntax documentation:

    replacement_field ::=  "{" [field_name] ["!" conversion] [":" format_spec] "}"
    field_name        ::=  arg_name ("." attribute_name | "[" element_index "]")*
    arg_name          ::=  [identifier | integer]
    

    So the field_name is either an integer or a valid Python identifier.

    Note that empty strings are not the only stings that are not valid identifiers; you cannot use strings with spaces in it either, or strings that start with a digit. Such strings can be used in a dictionary, just not as keyword arguments in Python code nor as field names in string formats.