Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can you format against a tuple but not a list?

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

like image 284
Matt Avatar asked Dec 15 '16 10:12

Matt


1 Answers

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.

like image 82
unutbu Avatar answered Oct 03 '22 09:10

unutbu