正如评论所指出的,你的
contains_alphabetic
和
contains_numeric
函数不会做你认为它们正在做的事情,因为它们在第一次迭代中过早终止。启动一个循环,检查当前字符(在循环的第一次迭代中,它将是字符串的第一个字符),然后立即基于该单个字符从函数返回一些内容,这当然会终止循环和函数。
其他建议:没有必要从
curses
.字符串已经有了
isalpha
和
isdigit
谓词可用。此外,让函数接受字符串参数进行迭代可能是个好主意。
如果你想回来
True
如果字符串中的任何字符满足条件/谓词,以及
False
否则(如果所有字符都不满足条件),则以下将是一个有效的实现:
def contains_alpha(string):
for char in string:
if char.isalpha():
return True # return True as soon as we see a character that satisfies the condition
return False # Notice the indentation - we only return False if we managed to iterate over every character without returning True
或者:
def contains_alpha(string):
found = False
for char in string:
if char.isalpha():
found = True
break
return found
或者:
def contains_alpha(string):
for char in string:
if char.isalpha():
break
else: # Notice indentation - special for-else syntax: If we didn't break out of the loop, execute the else
return False
return True
或者:
def contains_alpha(string):
return any(char.isalpha() for char in string)