Search code examples
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 = "[email protected]"
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:

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