9

Say I do the following:

>>> a = foo@bar.com
>>> 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?

john
  • 2,933
  • 4
  • 25
  • 45

5 Answers5

13

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!"
josh-fuggle
  • 2,666
  • 2
  • 23
  • 24
6

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.

João Neves
  • 895
  • 1
  • 6
  • 12
  • This use of `_` is actually quite well established, see [What is the purpose of the single underscore “_” variable in Python?](http://stackoverflow.com/q/5893163/699305). – alexis Mar 14 '17 at 13:09
4

This gives you an empty string if there's no @:

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

If you want to get the original string back when there's no @, use this:

    >>> domain = a.rpartition('@')[2]
sjcrowe
  • 41
  • 2
4

If you know there's always an @ in your string, domain = a.split('@')[1] is the way to go. Otherwise check for it first or add a try..except IndexError block aroudn it.

ThiefMaster
  • 285,213
  • 77
  • 557
  • 610
  • 1
    You might also consider `domain = a.partition('@')[2]`. This will set `domain` to `''` if there is no `@` in the string, and will also only split on the first `@` if there is more than one. – Karl Knechtel Apr 21 '11 at 10:16
2

This could work:

domain = a[a.index("@") + 1:]
Rumple Stiltskin
  • 7,691
  • 1
  • 18
  • 24