Skip to main content
 首页 » 编程设计

python之无法学习如何查看字符串中的单个字符,检查大小写或数字

2025年05月04日27youxin

我正在尝试为家庭作业编写一个简单的密码检查器,寻找至少一个大写字母、一个小写字母、一个数字,并且它需要是 6 个或更多字符。

我在这里和其他地方搜索了又搜索,但要么我读到的内容与我们的说明不符,要么回复比我更高级。我得到的任何帮助都会在我的作业中作为评论被引用。

这只是我的代码中检查大写字母的部分,它只查看整个字符串,而不是单个字符,我似乎找不到解决方案。

    passwd = input('enter password: ') ## we are actually using (sys.agrv)  
                                       ## but I am using this for testing 
    character = passwd[0:] 
    lcase_bad = False 
    for character in passwd: 
    if not character.islower() > 1: 
    lcase_bad = True 
 
    if lcase_bad: 
      print('Password must include lowercase letters ') 
    else: 
        print('password accepted') 

请您参考如下方法:

密码中的字符:

在这里,您将遍历输入的每个字母。

当您执行 if not character.islower() > 1: 时,它将始终为 True。 .islower() 返回 True 或 False,具体取决于字符串是否为大写字母。 不是 False == 1,因为 boolean 是 int 的子类。 不为真 == 0。两者都不大于一。


你可以这样做:

capital = False 
lowercase = False 
number = False 
if len(passwd) < 6: 
    print 'That was not more than 6 characters' 
else: 
    for character in passwd: 
        if character.islower():  
            lowercase = True 
        elif character.isupper(): 
            capital = True 
        elif character.isdigit(): 
            number = True 
        if capital and lowercase and number: 
            break 
    else:  
        print 'That did not have a capital letter, lowercase letter, and a digit' 

当然,如果您想告诉对方密码没有,这很有用。但是,您也可以只进行一项测试。