2013-12-10 98 views
1

我正在设计一个系统,允许用户输入一个字符串,以及由非字母数字字符数量确定的字符串的强度。积分应如下授予:每个非阿尔纳姆字符+1,最多3个非阿尔纳姆字符。Python - 查找字符串中的所有非字母数字字符

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 

我刚刚开始编码,所以我很抱歉,如果这看起来像一个非常初级的问题。

+0

你可能要考虑*正则表达式*。 – fuesika

+0

@pyStarter:'isalnum'的正则表达式让事情变得更加复杂无理。 – abarnert

回答

6

你可以简单地尝试:

bonus = min(sum(not c.isalnum() for c in pwd), 3) 
+0

请注意,这依赖于布尔值可以被强制转换为数字(使用sum())的实现细节,而不是False因此是1.这个单线程使用min()对总和和最大奖励进行编码。 –

+0

这不是Python中True为1的实现细节,它由语言保证。然而,对于新手来说,这非常神秘,特别是没有解释。 – abarnert

1

如果你想指望非字母串的数量,你可以说

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")) 
+0

*“最多3个非Alnum字符。”* – arshajii

+0

糟糕。我们走了。 – MxyL

0

没有与此代码的多个问题。

首先,if True:总是如此,所以"Nope"总是会发生,并且if False:永远不会是真的,所以这些东西都不会发生。我想你想的:

if pwd[count].isalnum(): 
    print "Nope" 
else: 
    print "Good job" 
    count = count + 1 
    number += 1 

另外,我觉得要增加count总是,不只是如果它是一个符号,所以:

if pwd[count].isalnum(): 
    print "Nope" 
else: 
    print "Good job" 
    number += 1 
count = count + 1 

同时,你需要一些类型的循环如果你希望这个发生一遍又一遍。例如:

while count < len(pwd): 
    if pwd[count].isalnum(): 
     # etc. 

不过,你真的不需要自己维护count,继续做pwd[count];您可以使用for循环此:

for ch in pwd: 
    if ch.isalnum(): 
     # etc. 

同时,当你做return从函数的最后一个值,你不与返回值做任何事情,当你调用功能。你需要的是:

number = non_alnum_2(total, pwd) 

而且,没有理由来传递totalnon_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 
相关问题