Python string.format (* variable)

I am reading a book to read, and it covers this example below.

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

Everything seems obvious, except for the star used at the end of the last line. The book cannot explain the use of this, and I hate to progress further without understanding anything.

Many thanks for your help.

+3
source share
4 answers

This argument unpacks the (kinda) operator.

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

coincides with

fun(1, 2, 3)

(for some called fun).

There is also a function definition function that 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]
+4
source

The operator *, often called the star or splat operator, decompresses iterability into function arguments, so in this case it is equivalent:

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

python .

+8

.

+1

*when used inside a function, it means that the variablenext one *is iterable and retrieved 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])

, eg:

 >>> a=[1,2,3,4,5]
 >>> print(*a)
 1 2 3 4 5
0
source

All Articles