1

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.

Anshul Vyas
  • 633
  • 9
  • 19
Harsh
  • 126
  • 6

7 Answers7

1

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'
Samwise
  • 68,105
  • 3
  • 30
  • 44
0

Find the index of @ and keep the first part

email = "myemail@email.com"
email = email[:email.index('@')]
print(email)

Output:

myemail
rdas
  • 20,604
  • 6
  • 33
  • 46
0

You can try like below:

email = "myemail@email.com"
a = email.split('@')
a[0]
0

Or you can make it with a split.

In [1]: "myemail@email.com".split("@")[0]                                                                                                     
Out[1]: 'myemail'
Martin Nečas
  • 593
  • 2
  • 9
0
email = "myemail@email.com"
a = email.split("@")[0]
print(a)

gives output:

myemail

email.split("a") returns a list ["myemail", "email.com"] from which you can take the first element using [0]

YulkyTulky
  • 886
  • 1
  • 6
  • 20
0

You could split the email into a list, using the @ as a separator, then print the first item in the list, which would be everything before the @. This would account for domain names of different length. For example, @yahoo.com is longer than @gmail.com, you'd have to account for the individual lengths.

email = "myemail@email.com"
a = email.split("@")[0]
print(a)

Or you can use the replace method as you are and do it on a case by case basis, but your splice is incorrect. The stop value is not included. So by your saying a = a.replace(a[-10:-1] , '') you haven't replaced the m from .com. If you were to instead say a = a.replace(a[-10:],'') you will replace everything from the -10th index to the end of the string.

Another potential solution would be to find the index of the @.

a = email[0:email.index('@')]
Brenden Price
  • 517
  • 2
  • 9
0

code:

email = "myemail@email.com"

new_email = email.replace(email[-10:],'')

print(new_email)

output: myemail