Is there a shorthand syntax for a sequence of throwaway variables?

后端 未结 3 1531
抹茶落季
抹茶落季 2021-01-22 07:42

Let\'s say you have a situation like this:

_, _, _, substring_1, _, substring_2 = some_string.split(\',\')

Is there a shorthand way of expressi

3条回答
  •  广开言路
    2021-01-22 08:14

    You could just use str.rsplit with a limit:

    >>> s = 'a,b,c,d,e,f'
    >>> s.rsplit(',', 3)  # i.e. split on at most three commas, from the right
    ['a,b,c', 'd', 'e', 'f']
    >>> _, d, _, f = s.rsplit(',', 3)
    >>> d
    'd'
    >>> f
    'f'
    

    If you upgrade to Python 3.x, you can use *_ to absorb an arbitrary number of elements (you'll get a SyntaxError in 2.x, though):

    >>> *_, d, _, f = s.split(',')
    >>> d
    'd'
    >>> f
    'f'
    

提交回复
热议问题