3

I'm reading a book to read and it covers this below example.

somelist = list(SPAM)
parts = somelist[0], somelist[-1], somelist[1:3]
'first={0}, last={1}, middle={2}'.format(*parts)

Everything seems clear apart from the star being used at the end of the last line. The book fails to explain the usage of this and I hate to progress on without full understanding things.

Many thanks for your help.

4

4 回答 4

8

The * operator, often called the star or splat operator, unpacks an iterable into the arguments of the function, so in this case, it's equivalent to:

'first={0}, last={1}, middle={2}'.format(parts[0], parts[1], parts[2])

The python docs have more info.

于 2012-05-01T15:19:35.870 回答
5

It's argument unpacking (kinda) operator.

args = [1, 2, 3]
fun(*args)

is the same as

fun(1, 2, 3)

(for some callable fun).

There's also star in function definition, which means "all other positional arguments":

def fun(a, b, *args):
    print('a =', a)
    print('b =', b)
    print('args =', args)

fun(1, 2, 3, 4) # a = 1, b = 2, args = [3, 4]
于 2012-05-01T15:21:04.183 回答
1

A comprehensive explanation about single and double asterisk form.

于 2012-05-01T16:37:59.967 回答
0

* when used inside a function means that the variable following the * is an iterable, and it extracted inside that function. here 'first={0}, last={1}, middle={2}'.format(*parts) actually represents this:

'first={0}, last={1}, middle={2}'.format(parts[0],parts[1],parts[2])

for example:

 >>> a=[1,2,3,4,5]
 >>> print(*a)
 1 2 3 4 5
于 2012-05-01T15:25:49.470 回答