Consider the following:
st = "Hi: %s, you are: %d"
x = ['user', 25]
st % x # Doesn't work
st % ("user", 25) # Works
st % (*x,) # Works
I just thought it was a very strange restriction
Ah, but you can "format against a list":
In [4]: '%s' % [1,2]
Out[4]: '[1, 2]'
The %
string interpolator can be followed by either a single non-tuple object or a tuple.
If it is a tuple, the arguments are unpacked and matched against placeholders in the strings. If the object is a single non-tuple object, then the entire object is passed to the placeholder in the string.
This somewhat manic behavior is part of what motivated the Python developers to introduce the syntactically cleaner str.format
method.
Also, from PEP 3101:
The '%' operator is primarily limited by the fact that it is a binary operator, and therefore can take at most two arguments. One of those arguments is already dedicated to the format string, leaving all other variables to be squeezed into the remaining argument. The current practice is to use either a dictionary or a tuple as the second argument, but as many people have commented, this lacks flexibility. The "all or nothing" approach (meaning that one must choose between only positional arguments, or only named arguments) is felt to be overly constraining.
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