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)
String len() It is valid to have a string of zero characters, written just as '' , called the "empty string". The length of the empty string is 0. The len() function in Python is omnipresent - it's used to retrieve the length of every data type, with string just a first example.
Use len to Check if a String in Empty in Python # Using len() To Check if a String is Empty string = '' if len(string) == 0: print("Empty string!") else: print("Not empty string!") # Returns # Empty string! Keep in mind that this only checks if a string is truly empty.
An empty string is a string instance of zero length, whereas a null string has no value at all. An empty string is represented as "" . It is a character sequence of zero characters. A null string is represented by null .
The None keyword is used to define a null value, or no value at all. None is not the same as 0, False, or an empty string. None is a data type of its own (NoneType) and only None can be None.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With