What does the asterisk do in *a, b, c = line.split()?

后端 未结 1 383
长情又很酷
长情又很酷 2021-01-16 06:30

Assume line is: \"Chicago Sun 01:52\".

What does *a, b, c = line.split() do? In particular, what is the significance of the a

相关标签:
1条回答
  • 2021-01-16 07:11

    Splitting that text by whitespace will give you:

    In [743]: line.split()
    Out[743]: ['Chicago', 'Sun', '01:52']
    

    Now, this is a 3 element list. The assignment will take the last two elements of the output and assign them to b and c respectively. The *, or the splat operator will then pass the remainder of that list to a, and so a is a list of elements. In this case, a is a single-element list.

    In [744]: *a, b, c = line.split()
    
    In [745]: a
    Out[745]: ['Chicago']
    
    In [746]: b
    Out[746]: 'Sun'
    
    In [747]: c
    Out[747]: '01:52'
    

    Look at PEP 3132 and Where are python's splat operators * and ** valid? for more information on the splat operators, how they work and where they're applicable.

    0 讨论(0)
提交回复
热议问题