我的两个python函数是否相互重叠?

时间:2018-01-03 19:46:03

标签: python regex function if-statement override

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

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

密码需要大写字母才能获得更高分    五    小写

这些结果我很满意。

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

The password needs capital letters for a higher score
5
LOWERCASE

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

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

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

2 个答案:

答案 0 :(得分: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"

答案 1 :(得分:0)

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

另见search() vs. match()