简体   繁体   English

如果拆分列表中的值为空,则返回False

[英]If Value in Split List is Empty Return False

I'm working on a script that allows users to input an email. 我正在编写一个允许用户输入电子邮件的脚本。 If the email has a 'username' and 'domain' such as username@domain.com, then the program should output that the email is an email. 如果电子邮件具有“用户名”和“域名”,例如username@domain.com,则程序应输出该电子邮件是电子邮件。 If the user enters something such as username@, then the program should output that the input is not a valid email address. 如果用户输入诸如username @之类的内容,则程序应输出输入不是有效的电子邮件地址。

The function should return True when the text is an email, otherwise it should return False. 当文本是电子邮件时,该函数应返回True,否则返回False。

I'm having a problem getting the program to return False when entering an address like 'username@' or '@gmail.com'. 输入“username @”或“@ gmail.com”这样的地址时,我遇到了让程序返回False的问题。

I currently have the following code: 我目前有以下代码:

text = ''
tokens = 0
split_counter = 0

def isEmail(text):
    tokens = text.split('@')
    split_counter = len(tokens)
    if split_counter == 2:
        print(text, '==> EMAIL')
    else:
        print(text, '==> NOT EMAIL')
    return

while True:
    text = input("Email: ")    
    if text == 'quit':
        print('Later!')
        break
    else:
        isEmail(text)

Thank you. 谢谢。

I would recommend using regex and looking at the other answers on StackOverflow for checking for a valid email. 我建议使用正则表达式并查看StackOverflow上的其他答案以检查有效的电子邮件。 But in response to your question, from what you commented above, it is not returning false when you try "@gmail.com". 但是在回答你的问题时,根据你上面的评论,当你尝试“@ gmail.com”时,它不会返回false。 This is because when you split a string by "@", it returns 这是因为当你用“@”分割字符串时,它会返回

string = "@gmail.com"
string.split("@")
>>> ['', 'gmail.com']

Therefore, the length of that returned list will be 2. You could make another check inside the split_counter list: 因此,返回列表的长度为2.您可以在split_counter列表中进行另一次检查:

if split_counter == 2 and tokens[0] != '':
    print(text, '==> EMAIL')

I would recommend printing whatever you have along the way as a way of debugging your code. 作为一种调试代码的方法,我建议您一路打印所有内容。 It'll help you avoid errors like this in the future. 它将帮助您避免将来出现这样的错误。 You knew that the condition had to be wrong, and the condition is only dependent on split_counter, so you could have printed split_counter to see what went wrong. 你知道条件必须是错误的,条件只依赖于split_counter,所以你可以打印split_counter来查看出错的地方。

The split method always return two strings if there is only one @ . 如果只有一个@split方法总是返回两个字符串。 For example: 例如:

>>> text="foo@"
>>> text.split('@')
['foo', '']

So you should check that the two returned strings have a length greater than zero. 所以你应该检查两个返回的字符串的长度是否大于零。

You can see the problem is split() function: 你可以看到问题是split()函数:

>>> text = "@gmail.com"
>>> tokens = text.split("@")
>>> tokens
['', 'gmail.com']

Best practice is to use regex to check valid emails instead of writing hard code: 最佳做法是使用regex来检查有效的电子邮件,而不是编写硬代码:

def isEmail(text):
    if len(text) > 6:
        if re.match(r'\b[\w.-]+@[\w.-]+.\w{2,4}\b', text) != None:
            # do something
    else:
        # do something

If you don't know what is regex , then this is probably the right time to learn it. 如果你不知道什么是regex ,那么这可能是学习它的最佳时机。

A simple solution could be to leverage all() and the fact, that bool("") is False for that: 一个简单的解决方案可能是利用all()和事实, bool("")False

>>> email = "@gmail.com"
>>> s = email.split("@")
>>> all(s)
>>> False

>>> email = "a@"
>>> s = email.split("@")
>>> all(s)
>>> False

>>> email = "a@gmail.com"
>>> s = email.split("@")
>>> all(s)
>>> True

But beware, that this code doesn't say anything about the "correctness" of an email adress. 但请注意,此代码并未说明电子邮件地址的“正确性”。 It only says something about whether a string could be split by @ and none of the parts is empty. 它只说明一个字符串是否可以被@拆分而且没有一个部分是空的。

For that purpose I would rely on validators provided by frameworks like Django or something like WTForms . 为此,我将依赖于Django等框架或类似WTForms之类的框架提供的验证器。

All you're missing is another check on line 11: 所有你遗失的是第11行的另一张检查:

if split_counter == 2 and len(tokens[0]) > 0 and len(tokens[1]) > 0:
    print(text, '==> EMAIL')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM