我的两个python函数是否相互重叠? [关闭]

问题描述 投票:-2回答:2
import re
score = 0

capital_letters = r'[A-Z]'
a = re.compile(capital_letters)

lowercase_letters = r'[a-z]'
b = re.compile(lowercase_letters)

def increase_score (aValue, aScore):
  aScore += aValue
  return aScore

def upper_score(test_string, aScore):
  if re.match(a, test_string):
    aScore = increase_score(5, aScore)
    print (aScore)
    print("UPPERCASE")
  else:
    print("The password needs capital letters for a higher score")


def lower_score(test_string, aScore):
    if re.match(b, test_string):
      aScore = increase_score(5, aScore)
  print (aScore)
  print("LOWERCASE")
else:
  print("The password needs lowercase letters for a higher score")

password = input("Enter a password to check")
upper_score(password, score)
lower_score(password, score)

如果我输入所有大写字母,我得到这个输出:

5
UPPERCASE
The password needs lowercase letters for a higher score

如果我输入所有小写字母,我得到这个输出:

密码需要大写字母才能获得更高的分数5 LOWERCASE

这些结果我很满意。

问题是当我结合大写和小写字母时,我得到了这个结果:

The password needs capital letters for a higher score
5
LOWERCASE

1)即使有大写和小写字母,分数仍然是5而不是10。

2)即使字符串中有大写字母,大写字母的正则表达式也会停止工作。

谢谢!!!我希望我能很好地解释这一点。

python regex function if-statement override
2个回答
0
投票

re.match在给定字符串的BEGINNING处查找字符。请改用re.search

另见search() vs. match()


1
投票

简要

你甚至不需要正则表达式。 Python有isupper()islower()函数可用。


See code in use here

passwords = [
    "all lowercase letters",
    "ALL UPPERCASE LETTERS",
    "Mixed lowercase and UPPERCASE letters"
]

def lower_score(string, weight):
    if any(s.islower() for s in string):
        print "Contains: LOWERCASE"
        return weight
    else:
        print "Message: The password needs lowercase letters for a higher score"
    return 0

def upper_score(string, weight):
    if any(s.isupper() for s in string):
        print "Contains: UPPERCASE"
        return weight
    else:
        print "Message: The password needs capital letters for a higher score"
    return 0

for password in passwords:
    print "Password: " + password
    score = 0
    score += lower_score(password, 5)
    score += upper_score(password, 5)
    print "Score: " + str(score) + "\n"
© www.soinside.com 2019 - 2024. All rights reserved.