Python-查找字符串中的所有非字母数字字符
我正在设计一个系统,允许用户输入字符串,字符串的强度由非字母数字字符的数量决定。每一个非alnum字符最多可获得3个非alnum字符+1的点数Python-查找字符串中的所有非字母数字字符,python,function,Python,Function,我正在设计一个系统,允许用户输入字符串,字符串的强度由非字母数字字符的数量决定。每一个非alnum字符最多可获得3个非alnum字符+1的点数 def non_alnum_2(total,pwd): count = 0 lid = 3 number = 0 if pwd[count].isalnum(): if True: print "Nope" if False: print "Good job" count = count +
def non_alnum_2(total,pwd):
count = 0
lid = 3
number = 0
if pwd[count].isalnum():
if True:
print "Nope"
if False:
print "Good job"
count = count + 1
number += 1
if number > lid:
number = lid
return number
total = 0
number = 0
pwd = raw_input("What is your password? ")
non_alnum_2(total, pwd)
print total
total += number
我刚刚开始编写代码,如果这看起来像是一个非常初级的问题,我很抱歉 您只需尝试:
bonus = min(sum(not c.isalnum() for c in pwd), 3)
如果要计算非alpha字符串的数量,可以说
def strength(string):
'''Computes and returns the strength of the string'''
count = 0
# check each character in the string
for char in string:
# increment by 1 if it's non-alphanumeric
if not char.isalpha():
count += 1
# Take whichever is smaller
return min(3, count)
print (strength("test123"))
此代码存在多个问题 首先,
如果为真:
总是真的,所以的“Nope”
总是会发生,而如果为假:
从来都不是真的,所以这些事情都不会发生。我想你想要这个:
if pwd[count].isalnum():
print "Nope"
else:
print "Good job"
count = count + 1
number += 1
此外,我认为您希望始终递增计数
,而不仅仅是如果它是一个符号,因此:
if pwd[count].isalnum():
print "Nope"
else:
print "Good job"
number += 1
count = count + 1
同时,如果你想让这种事情一次又一次地发生,你需要某种循环。例如:
while count < len(pwd):
if pwd[count].isalnum():
# etc.
同时,当您从函数末尾返回值时,调用函数时,您不会对返回的值执行任何操作。您需要的是:
number = non_alnum_2(total, pwd)
此外,这里没有理由将total
传递给non_alnum_2
。事实上,它一点用处都没有
因此,把所有这些放在一起:
def non_alnum_2(pwd):
lid = 3
number = 0
for ch in pwd:
if ch.isalnum():
print "Nope"
else:
print "Good job"
number += 1
if number > lid:
number = lid
return number
pwd = raw_input("What is your password? ")
number = non_alnum_2(pwd)
print number
“最多3个非alnum字符。”请注意,这取决于实现细节,即布尔值可以强制转换为数字(使用sum()),因此not False为1。这个一行代码使用min()对总和和最大加值进行编码。在Python中,True不是1,而是由语言保证的。但是,这对于新手来说是非常神秘的,尤其是没有解释。你可能想考虑正则表达式。@ PyScter:一个正则表达式,用于<代码> iAlnNu< /C>只是让事情变得更复杂。
def non_alnum_2(pwd):
lid = 3
number = 0
for ch in pwd:
if ch.isalnum():
print "Nope"
else:
print "Good job"
number += 1
if number > lid:
number = lid
return number
pwd = raw_input("What is your password? ")
number = non_alnum_2(pwd)
print number