Python, split tuple items to single stuff

后端 未结 4 436
囚心锁ツ
囚心锁ツ 2020-12-16 12:32

I have tuple in Python that looks like this:

tuple = (\'sparkbrowser.com\', 0, \'http://facebook.com/sparkbrowser\', \'Facebook\')

and I wa

4条回答
  •  没有蜡笔的小新
    2020-12-16 12:57

    Best not to use tuple as a variable name.

    You might use split(',') if you had a string like 'sparkbrowser.com,0,http://facebook.com/sparkbrowser,Facebook', that you needed to convert to a list. However you already have a tuple, so there is no need here.

    If you know you have exactly the right number of components, you can unpack it directly

    the_tuple = ('sparkbrowser.com', 0, 'http://facebook.com/sparkbrowser', 'Facebook')
    domain, level, url, text = the_tuple
    

    Python3 has powerful unpacking syntax. To get just the domain and the text you could use

    domain, *rest, text = the_tuple
    

    rest will contain [0, 'http://facebook.com/sparkbrowser']

提交回复
热议问题