9

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?

5 Answers 5

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!"
Sign up to request clarification or add additional context in comments.

2 Comments

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.
Can you please explain when to use split and when to use partition?
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.

1 Comment

This use of _ is actually quite well established, see What is the purpose of the single underscore “_” variable in Python?.
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.

1 Comment

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.
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]

Comments

2

This could work:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.