首页 > 解决方案 > 如何检查字符串是否有个性化错误?

问题描述

我正在尝试制作一个程序,在其中输入姓名和姓氏,代码检查名称是否无效(下面的无效列表)。如果它有任何失效,它会要求我再次说出这个名字并给我一个所有失效的列表。无效列表(我也会显示代码版本): - 名称有数字 - 名称有符号 - 名称没有空格 - 有多个空格 - 名称之一太短或太长 -名称的第一个字母是空格 - 名称的最后一个字母是空格

我不能在这里使用异常,因为这些不是代码错误。我已经用 Ifs 做到了,但它达到了一个只有很多 Ifs 才能使其可行的地步。

def has_digits(name):
    digits = any(c.isdigit() for c in name)
    if digits == True:
        return True
        print("Your name has digits.")
    else:
        return False


def has_symbols(name):
    symbols = any(not c.isalnum() and not c.isspace() for c in name)
    if symbols == True:
        return True
        print("Your name has symbols.")
    else:
        return False


def has_no_spaces(name):
    spaces = any(c.isspace() for c in name)
    if not spaces == True:
        return True
        print("You only gave me a name.")
    else:
        return False


def many_spaces(name):
    m_s = name.count(' ') > 1
    if m_s == True:
        return True
        print("Your name has more than one space.")
    else:
        return False


def unrealistic_length(name, surname):
    length= (float(len(name)) < 3 or float(len(name)) > 12) or float(len(surname)) < 5 or float(len(surname) > 15)
    if length == True:
        return True
        print("Your name has an unrealistic size.")
    else:
        return False


def first_space(name):
    f_s = name[0] == " "
    if f_s == True:
        return True
        print("The first letter of your name is a space.")
    else:
        return False


def last_space(name):
    l_s = name[-1] == " "
    if l_s == True:
        return True
        print("The last letter of your name is a space.")
    else:
        return False


name = "bruh browski"
namesplit = name.split(" ")
name1 = namesplit[0]
name2 = namesplit[1]

print(has_digits(name))
print(has_symbols(name))
print(has_no_spaces(name))
print(many_spaces(name))
print(unrealistic_length(name1, name2))
print(first_space(name))
print(last_space(name))

也许印刷品本身不应该在defs中。我不知道。我几乎可以肯定做一个 for 循环是要走的路,但我无法想象该怎么做。

结果:

False
False
False
False
False
False
False

标签: python

解决方案


您用来准确定义每个“无效”的方法将必须保留,除非您可以用做同样事情的其他方法替换它们。但是您可以使用生成器表达式一次检查所有这些条件:

if any(is_invalid(name) for is_invalid in [
        has_digits, has_symbols, has_no_spaces, many_spaces, unrealistic_length, first_name, last_name
        ]):
    # then this string is invalid
# otherwise, all of those returned false, meaning the string is valid.

然后,您可以使用该条件来确定何时停止询问用户,或者您需要什么时候停止询问。

如果你不想单独定义所有这些函数,你也可以使用 lambdas 来做同样的事情。


作为旁注,在生产中实际使用它来检查名称的有效性之前,我建议查看Falsehoods Programmers Believe about Names列表。不过,即使它与您的用例无关,这也是一本有趣的书。


推荐阅读