Py学习  »  Python

如何在python中查找字符串中的任何字符是否为数字。是数字和数字。isdigit不起作用

Sara • 3 年前 • 1409 次点击  

我需要确定字符串中是否有字母和数字字符。我测试字母字符的代码似乎运行良好,但只有当所有字符都是数字时,数字才起作用,如果有的话,则不起作用。

有效的字母代码:

from curses.ascii import isalnum, isalpha, isdigit

password = input("Enter your password: ")

def contains_alphabetic():
    for i in password:
        if isalpha(i):
            print("Valid")
            return True
        else:
            print("Invalid")
            return False

contains_alphabetic()

如果至少有一个字符是字母,则返回“Valid”,如果没有,则返回“Invalid”,这就是我想要的。

def contains_numeric():
    for j in password:
        if isdigit(j):
            print("Valid")
            return True
        else:
            print("Invalid")
            return False

contains_numeric()

只有当所有字符都是数字时,才会返回“Valid”,如果至少有一个字符是数字,则不会返回。我该怎么解决这个问题?

此外,我还试着使用is。numeric()而不是is。digit()甚至不会导入。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/128353
文章 [ 2 ]  |  最新文章 3 年前
Tomas Orihuela
Reply   •   1 楼
Tomas Orihuela    3 年前

对于alpha检查,不需要循环检查密码中的每个字符。只需使用检查字符串。用于字符串的isalpha()。对于数字,你必须循环使用密码。下面的示例显示了一个使用行理解的选项。它使用。isdigits()用于字符串。注意,不需要导入任何模块。

password = "Company12#"

print("Does password only contain letters?: {}".format(password.isalpha()))
# returns False

print("Does password contain a number?: {}".format(any(char.isdigit() for char in password)))
# returns True
Paul M.
Reply   •   2 楼
Paul M.    3 年前

正如评论所指出的,你的 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)