Search code examples
pythonstring-parsing

"ValueError: list.index(x): x not in list" in Python, but it exists


I want to use Python to pull the username from an email address. The solution I thought of was to append the email address into a list, find the index of the @ symbol, and then slice the list until I found the index.

My code is:

#!/usr/bin/env python<br/>
email = raw_input("Please enter your e-mail address: ")
email_list = []
email_list.append(email)
at_symbol_index = email_list.index("@")
email_username = email_list[0:at_symbol_index]
print email_username

But, everytime I run the script, it returns the error:

ValueError: list.index(x): x not in list

What's wrong with my code?


Solution

  • The reason for this is that you are making a list containing the string, so unless the string entered is "@", then it is not in the list.

    To fix, simply don't add the email address to a list. You can perform these operations on a string directly.

    As a note, you might want to check out str.split() instead, or str.partition:

    email_username, _, email_host = email.partition("@")