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


the empty string ('') pertectly valid key dictionary, can not reference using 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 way of referencing key ... dictionary key! can not convert data tuples; bit of background: doing auto-formatting based on generic format spec gets converted format string syntax using dicts data formatting. is, can not this:

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

the data must passed format **data (basically, because doing generic .format(**data) in formatter class)

you can't use empty string. format strictly limits keys valid python identifiers, means have have @ least 1 letter or underscore @ start.

from grammar in format string syntax documentation:

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

so field_name either integer or valid python identifier.

note empty strings not stings not valid identifiers; cannot use strings spaces in either, or strings start digit. such strings can used in dictionary, not keyword arguments in python code nor field names in string formats.


Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -