Rackaid
Rackaid

Reputation: 9

how to check last characters of a string

I'm trying to make a program that only accepts valid email addresses without using anything super fancy. I'm trying to use negative indexing to get the last characters of the string the user enters and make sure the input is valid. I can't seem to figure out how to check the last characters of the string using this method. Here's what I have so far:

email = 'None'
while email != '@gmail.com':
  email = input("Please enter your email. It must be a valid Gmail email: ")
  if '@gmail.com' in email[-11:0]:
    continue
  else:
    print("Enter a valid Gmail email.")                

I've tried rearranging the values in the index and changing the values themselves, but no matter what it always says to enter a valid email even if it does end in @gmail.com. I'm not trying to allow any valid email, I only care about Gmail emails so I need to work for this only.

Upvotes: 0

Views: 1337

Answers (3)

Dinesh Neupane
Dinesh Neupane

Reputation: 402

str='[email protected]'
sliced_str=str[-10:]

this gives a string with last 10 chars in string. But a better approach would be to use endswith() function like this:

if str.endswith("@gmail.com")

you also need to check if the user input has multiple @'s as well. SO, to consider both you can do something like this:

if str.count('@')==1 and str.endswith("@gmail.com")

To address the comments, you can create a simple function like this to check the mail address like this:

def check_mails(mail_address, dom_list):
    for i in dom_list:
        if mail_address.endswith(i):
            return True
    return False

and in your if condition :

if str.count('@')==1 and check_mails(str, ['@yahoo.com', '@gmail.com', '@hotmai.com'])

for checking if the user has intput only '@gmail.com' you can do that with the size of string like this: (considering an email has at least 3 characters before domain name)

 if str.count('@')==1 and len(str)>=13 and str.endswith("@gmail.com")

Upvotes: 3

Daniel Giger
Daniel Giger

Reputation: 2543

If you want to stick with negative indexing, you need to get rid of the 0. Also, you only need the last 10 characters to match '@gmail.com'. This should work better: email[-10:].

In email[-11:0], the 0 after the colon makes it try to match all characters whose indices are greater than or equal to the length of the string minus 11, and also less than 0. There aren't any indices in that range, so it won't match anything.

Upvotes: 0

BruceWayne
BruceWayne

Reputation: 23283

You can use endswith:

if email.endswith("@gmail.com"): 

Upvotes: 0

Related Questions