python - 如何知道字符串中是否有数字

标签 python python-3.x string numbers int

我的任务是创建一个函数,如果单词中有数字(0-9)则返回 True,如果单词中没有数字则返回 False:

def has_digits(string):
    for r in range (0,10)
    if r in string:
        return 'True'
    else: return 'False'

print(has_digits('Python3'))

通常我有这样的错误消息:

TypeError: 'in <string>' requires string as left operand, not int

最佳答案

def has_digits(string):
    return any(char.isdigit() for char in string)

print(has_digits('abc1'))

你的例子应该像这样工作:

def has_digits(string):
    b = False
    for r in range(0, 10):
        if str(r) in string:
            b = True
    return b


print(has_digits('Python3'))

您应该已经解析了 str(r),其次您的函数将检查 0 是否在您的字符串中,并立即返回 false。不会针对循环中的其余值运行。

关于python - 如何知道字符串中是否有数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57656968/

相关文章:

python - 网页抓取 : scrape multiple webs by Python

python - 计算矩阵列平均值

python - 如何在 Django 模板中添加注释?

javascript - 在 JavaScript 中用下划线替换空格?

python - 从动词列表中检索动词

c++ - std::string 复制构造函数段错误

python celery - ImportError : No module named _curses - while attempting to run manage. py celeryev

python - 图例中的多行(具有不同的标记)

python - 如何在python中处理结构化语言文件

python - 迭代字典的键并对其作为数据帧的值执行切片