1
#Takes user's email and stores it in a variable
userEmail = input("Please enter email: ").lower()
while '@' not in userEmail or '.com\' not in userEmail or userEmail == '':       #Checks if email has a valid format
     if (userEmail == ''):
         userEmail = input("Field is empty. Please enter an email address: ").lower().strip()
     else:
         userEmail = input("\nIncorrect format. Please re-enter email address: ").lower().strip()

So the code above is supposed to get an email address from a user and it error checks for if the user put in a .com and @ when inputting.

However, when I run the code; if the user puts is name@**@**gmail.com or name@gmail.com**m** it takes it as the right format.

What is a way to limit the number of characters a user can input on after a certain character within a string?

Ahmad Khan
  • 2,655
  • 19
  • 25
B k
  • 11
  • 1

1 Answers1

1

What is a way to limit the number of characters a user can input on after a certain character within a string?

To limit the number of characters after the . to, e.g., between 2 and 4, you can use rpartition:

while True:
    email = input("Enter a valid email address: ").strip()

    if "@" in email:
        if 2 <= len(email.rpartition(".")[-1]) <= 4:
            # TLD length is acceptable; stop prompting
            break

print("You entered {e}.".format(e=email))

...checks for if the user put in a '.com' and '@' when inputting.

If these are your actual criteria:

email = None

while ("@" not in email) or not email.endswith(".com"):
    email = input("Enter a valid email address: ").strip()

print("You entered {e}.".format(e=email))

This still doesn't come close to format-validating an email address, though. While that's not what you asked, if you're interested, various approaches are discussed in answers to this question.

kungphu
  • 4,592
  • 3
  • 28
  • 37