Zenettii
Zenettii

Reputation: 393

Python string .format(*variable)

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.

Upvotes: 4

Views: 1694

Answers (4)

Vidul
Vidul

Reputation: 10546

A comprehensive explanation about single and double asterisk form.

Upvotes: 1

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251051

* 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

Upvotes: 0

Gareth Latty
Gareth Latty

Reputation: 89067

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.

Upvotes: 9

Cat Plus Plus
Cat Plus Plus

Reputation: 129894

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]

Upvotes: 5

Related Questions