Skip to main content
 首页 » 编程设计

python之如何在没有 try/except 或 str.isdigit 的情况下检查字符串是否包含数字

2025年05月04日22insus

NUMBERS = "123456789" 
 
def digit_checker(x): 
 
    for t in  x: 
        if t  in NUMBERS: 
           y = True 
        else: 
           y = False 
    return y 
 
 
 
 sentence = input("Enter a string to check if its all digits: ") 
 checker = digit_checker(sentence) 
 print(checker) 

如标题所述,如果不使用 str.isdigit 或 try/except,我将如何找到字符串是否包含所有数字。代码不断检查第一个字符而不是全部。我该如何解决?

请您参考如下方法:

NUMBERS = "123456789" 
 
def digit_checker(x): 
    y = True 
    for t in  x: 
        if t not in NUMBERS: 
           y = False 
    return y