Python: using line splitting and tuple return?

Let's say I do the following:

>>> a = foo@bar.com >>> uname, domain = a.split('@') 

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

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

Is there a better way to split a into a tuple and discard its uname?

+8
python
source share
5 answers

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

If you know that the string will have a “@” character, you can simply do the following:

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

If it is likely that you do not have the '@' character, then one of the following is suggested:

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

or

 try: domain = a.split('@')[1] except IndexError: print "Oops! No @ symbols exist!" 
+13
source share

You can use your own coding style and specify something like “use '_” because you don’t care about variables whose value you want to ignore. ”This is common practice in other languages ​​such as Erlang.

Then you can simply do:

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

And according to the rules you specified, the value in the _ variable should be ignored. As long as you consistently apply the rule, you should be fine.

+6
source share

If you know , your line always has @ , domain = a.split('@')[1] is the path. Otherwise, check it first or add a try..except IndexError block.

+4
source share

This gives you an empty string if not @:

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

If you want to return the original string when there is no @, use this:

  >>> domain = a.rpartition('@')[2] 
+4
source share

This might work:

 domain = a[a.index("@") + 1:] 
+2
source share

All Articles