Question

Say I have the following code:

from urlparse import urlparse
parsed_url = urlparse(url)
scheme, netloc, path = parsed_url[0], parsed_url[1], parsed_url[2]

Is there a more elegant or short way of assigning those three variables? It looks a bit messy to write parsed_url three times (I am expecting something other than renaming parsed_url to something shorter).

Était-ce utile?

La solution

You can cut the tuple in half:

scheme, netloc, path = parsed_url[:3]

Or, to make it explicit that there are six values and you're ignoring three of them, you could assign to a dummy variable named _:

scheme, netloc, path, _, _, _ = parsed_url

Autres conseils

parsed_url[:3] will create a subtuple consisting of exactly the wanted parts.

So

scheme, netloc, path = parsed_url[:3]

will do what you need.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top