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
  • 3,043
  • 5
  • 27
  • 48

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
  • 3,097
  • 2
  • 26
  • 27
  • There's a reason why split and partition both exist. Sometimes split is the right thing to use, but this is not one of those times. – John La Rooy Apr 21 '11 at 10:32
  • 1
    Can you please explain when to use split and when to use partition? – john Apr 21 '11 at 21:40
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
  • 937
  • 1
  • 6
  • 13
  • 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
  • 310,957
  • 84
  • 592
  • 636
  • 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
  • 9,597
  • 1
  • 20
  • 25