pythonstringreplaceobject-slicing

Removing set of characters from the end of the string


I want to remove @email.com from this string and also as such that even if the "myemail" part is changed the code should still work I did this:

email = "myemail@email.com"
a = a.replace(a[-10:-1],'')
print(a)

Output:

myemailm

I wanted to remove that 'm' as well but i can't find a way to do so.

Thanks in advance.


Solution

  • Your slice is specifically excluding the last character. You're also making things more complicated than they need to be by using both a slice and a replace; any one of these on its own will do the job more simply:

    >>> "myemail@email.com"[:-10]
    'myemail'
    >>> "myemail@email.com".replace("@email.com", "")
    'myemail'
    >>> "myemail@email.com".split("@")[0]
    'myemail'