5

I am making algorithm for checking the string (e-mail) - like "E-mail addres is valid" but their are rules. First part of e-mail has to be string that has 1-8 characters (can contain alphabet, numbers, underscore [ _ ]...all the parts that e-mail contains) and after @ the second part of e-mail has to have string that has 1-12 characters (also containing all legal expressions) and it has to end with top level domain .com

email = raw_input ("Enter the e-mail address:")
length = len (email)
if length > 20 
    print "Address is too long"
elif lenght < 7:
    print "Address is too short"  
if not email.endswith (".com"):   
    print "Address doesn't contain correct domain ending"   
try:
    first_part = len (splitting[0])
    second_part = len(splitting[1])  

    account = splitting[0]
    domain = splitting[1] 

    list = "abcdefghijklmopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_."

    for c in account: 
        if c not in list:
            print "Invalid char", "->", c,"<-", "in account name of e-mail"

    for c in domain:
        if c not in list:
            print "Invalid char", "->", c,"<-", "in domain name of  e-mail"

    if first_part == 0:
        print "You need at least 1 character before the @"
    elif first_part> 8:
        print "The first part is too long"
    if second_part == 4:
        print "You need at least 1 character after the @"
    elif second_part> 16:
        print "The second part is too long"
except IndexError:
        print ""The address must consist of 2 parts connected with symbol @,\
 and ending must be .com"

    if first_part > 0 and first_part < 8 and second_part >4 and second_part < 16:
       print "Valid e-mail address"
Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
That_User
  • 929
  • 2
  • 7
  • 25
  • 8
    Have you attempted to solve this? post what you've tried rather than just a specification. – Chris Jun 15 '12 at 16:13
  • 1
    Have you Googled, "Email address validation" or "Email regex" or "How can I verify if an email address is real"? What have you tried? See: http://stackoverflow.com/faq#questions and http://stackoverflow.com/faq#dontask. Just for the record, if you show what you've done so far you will most likely earn back your -1's – Chris Pfohl Jun 15 '12 at 16:14
  • I'm a first year student at information science and we are just starting with python...this is our first weekend assignment – That_User Jun 15 '12 at 16:16
  • http://stackoverflow.com/search?q=E-Mail+address+validation+[python] – mensi Jun 15 '12 at 16:17
  • This is not really a Python related question, as it applies to almost every programming language. Take a look at this http://www.regular-expressions.info/email.html – leonsas Jun 15 '12 at 16:17
  • email = raw_input ("Enter the e-mail address:") length = len (email) if length in range (5, 12):      print "length is good" elif length <5:      print "Address is too short!" elif length> 12:      print "Address is too long" -------------------------------------------------------------------- this is the best i can do with my knowledge....and we cant use regular expressions, we are going to learn them later... – That_User Jun 15 '12 at 16:18
  • @user1459182 edit your question to improve it, don't post code in comments – mensi Jun 15 '12 at 16:19
  • Do you know about `for` loops? – Chris Pfohl Jun 15 '12 at 16:21
  • Possible duplicate: http://stackoverflow.com/questions/8022530/python-check-for-valid-email-address – Josh Mein Jun 15 '12 at 16:21
  • @JoshMein Not a dupe. He is explicitly disallowed from using regex. – Chris Pfohl Jun 15 '12 at 16:21
  • 4
    Also, look up python's `split` function and consider how you could use that on the entered email address. (Hint: it's useful at least twice) – Chris Pfohl Jun 15 '12 at 16:22
  • @Christopher Pfohl I found the duplicate before he made his most recent edit, and I did not notice the most recent stipulations when I posted it. Still I am pretty sure even without regex there are other possible dups for this question. It has been asked countless times on SO. – Josh Mein Jun 15 '12 at 16:26
  • split method uses spaces as separators so I can split the adres after and before the @ but still how to compare all legal expressions in these 2 parts of email...email.split("@") – That_User Jun 15 '12 at 16:31
  • Write out how you would do this on paper. `take first part of string and make sure it has a certain amount of characters`...`make sure the last four characters are .com` and then go through each part and solve it. – Noah Clark Jun 15 '12 at 16:32
  • 4
    Yes he's asking a homework question and yes he's new to the site and went about asking the wrong way but I was under the impression homework questions are allowed on SO. There's nothing wrong with this question now that he's added the code he has so far. I don't think we should give him a working solution, obviously, but I do think it should be re-opened. – Paolo Bergantino Jun 15 '12 at 16:50
  • 1
    Starting to get grasp on this problem, but I still need help...as you can see I'm still new to Python and this site, so apologies for inconvenience.. – That_User Jun 15 '12 at 17:55
  • Have you tried playing around in a python interpreter? Give IDLE a shot and have a good read of http://docs.python.org/library/stdtypes.html#string-methods – Alex L Jun 15 '12 at 20:45
  • OMG...so much...basically you can do anything with that... – That_User Jun 16 '12 at 23:53
  • Instead of 20 edits (which also caused it to become Community Wiki meaning no points are now awarded) you could wait until you have finished and do one edit.. – Shadow The GPT Wizard Jun 17 '12 at 08:09
  • I am not here for points, I am here for learning Python and trying to get right answer...and if possible to help someone – That_User Jun 17 '12 at 09:51

3 Answers3

3

Regular expressions FTW!

import re

address = 'test@gmail.com'
if re.match(r'^[a-z0-9_]{1,8}@[a-z0-9_]{1,8}\.com$', address, re.IGNORECASE):
  print 'valid'
else:
  print 'invalid'

A shorter regular expression (as the comments note) would be r'^\w{1,8}@\w{1,8}\.com$'

I don't know if that's what your teacher is aiming for, but regex are always good to know :)

kichik
  • 33,220
  • 7
  • 94
  • 114
  • Fixed some subtle bugs. You had `\\.` instead of `\.` (the first matches a literal `\ ` followed by any character, the second matches a literal `.`, which is what you intended.) I also cleaned up your character classes - using `\d` instead of `0-9`, and `a-zA-Z` instead of the ignore-case flag, which may not work like you expect for international users. – Li-aung Yip Jun 15 '12 at 23:19
  • 2
    I really resent this edit of yours. (1) You changed my wording and removed FTW (2) you added the escaping bug when you added the `r''` prefix (3) you introduced a bug into the code where the total length of what comes after `@` can be 16 and not 12 (4) you changed my coding style and made the code less verbose with the removal of `re.I`. If you have issues with my answer, leave a comment. Don't go around messing with other people's wording and code. – kichik Jun 15 '12 at 23:56
  • `\w` could be used instead of `[a-zA-Z\d_]` – jfs Jun 16 '12 at 00:19
  • You're right. I was going for verbosity, but it's definitely worth mentioning the shorter syntax. – kichik Jun 16 '12 at 02:58
2

If I understood well, you got everything working, except the part of finding invalid chars. Is that true?

Do you know the for loop? It may be helpful to you. Just get the parts of the e-mail:

account = splitting[0]
domain = splitting[1]

Then, iterate over each part. It will yield a character each time. If this char is not in the set of allowed ones, you print a message:

for c in account:
    if c not in "abcdefghijklmopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_.":
        print "Invalid char", c, "in e-mail"

for c in domain:
    if c not in "abcdefghijklmopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_.":
        print "Invalid char", c, "in e-mail"

This is not a very elegant solution (one could use string.ascii_letters+string.digits+"._" instead of "abcdefghijklmopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_.", for example, or list comprehesions), but I bet it is sufficiently understandable for a new user.

brandizzi
  • 26,083
  • 8
  • 103
  • 158
  • True, invalid chars was the main problem We can agree this is not a very elegant solution, but it will sure do the trick. – That_User Jun 15 '12 at 23:02
1

Construct a validate email method, with two parameters the email address to validate and a list of valid domains.

def validEmail(email, domains):

    length = len(email)

    index = email.find('@')

    if len(email[0:index]) <= 8 and len(email[0:index]) > 0:
        dot = email.find('.')
        if (len(email[index + 1:]) - dot) <= 12:
            if index+1==dot:
                return False
            else:
                for i in domains:
                    if email[dot + 1:] == i:
                        return True
    return False

domains = ['com', 'org', 'co.uk']

email = raw_input ("Enter the e-mail address:")
print validEmail(email, domains)
Robert
  • 2,222
  • 2
  • 21
  • 36
  • 1
    You've just invalidated your code by undoing my edit. I can't roll-back your edit and don't want to get into an edit war with anyone. However, if could please re-instate the spaces you've just removed I'd be grateful. – Ben Jun 15 '12 at 22:12