python – Split tuple items to separate variables

python – Split tuple items to separate variables

Python can unpack sequences naturally.

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

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]

python – Split tuple items to separate variables

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

Leave a Reply

Your email address will not be published. Required fields are marked *