Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Using split on a string and returning a tuple?

Tags:

python

Say I do the following:

>>> a = [email protected]
>>> uname, domain = a.split('@')

But what if I only ever want domain, and never uname? For example, if I only ever wanted uname and not domain, I could do this:

>>> uname, = a.split('@')

Is there a better way to split a into a tuple and have it throw away uname?

like image 837
john Avatar asked Apr 21 '11 10:04

john


2 Answers

To take into account some of the other answers, you have the following options:

If you know that the string will have an '@' symbol in it then you can simply do the following:

>>> domain = a.split('@')[1]

If there is a chance that you don't have an '@' symbol, then one of the following is suggested:

>>> domain = a.partition('@')[2]

Or

try:
    domain = a.split('@')[1]
except IndexError:
    print "Oops! No @ symbols exist!"
like image 169
josh-fuggle Avatar answered Sep 30 '22 01:09

josh-fuggle


You could use your own coding style and specify something like "use '_' as don't care for variables whose value you want to ignore". This is a general practice in other languages like Erlang.

Then, you could just do:

uname, _ = a.split('@')

And according to the rules you set out, the value in the _ variable is to be ignored. As long as you consistently apply the rule, you should be OK.

like image 37
João Neves Avatar answered Sep 30 '22 03:09

João Neves