首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >检查字符串是否包含数字

检查字符串是否包含数字
EN

Stack Overflow用户
提问于 2013-11-08 20:37:06
回答 15查看 488.6K关注 0票数 260

我发现的大多数问题都是基于这样一个事实,即他们在数字中寻找字母,而我在寻找数字中的数字,我希望它是一个无数的字符串。我需要输入一个字符串并检查它是否包含任何数字,以及它是否拒绝它。

如果所有字符都是数字,则函数isdigit()仅返回True。我只想看看用户是否输入了一个数字,比如像"I own 1 dog"之类的句子。

有什么想法吗?

EN

回答 15

Stack Overflow用户

回答已采纳

发布于 2013-11-08 20:38:23

您可以使用带有str.isdigit函数的any函数,如下所示

>>> def has_numbers(inputString):
...     return any(char.isdigit() for char in inputString)
... 
>>> has_numbers("I own 1 dog")
True
>>> has_numbers("I own no dog")
False

或者,您可以使用正则表达式,如下所示

>>> import re
>>> def has_numbers(inputString):
...     return bool(re.search(r'\d', inputString))
... 
>>> has_numbers("I own 1 dog")
True
>>> has_numbers("I own no dog")
False
票数 391
EN

Stack Overflow用户

发布于 2013-11-08 20:39:58

您可以组合使用anystr.isdigit

def num_there(s):
    return any(i.isdigit() for i in s)

如果字符串中存在数字,该函数将返回True,否则返回False

演示:

>>> king = 'I shall have 3 cakes'
>>> num_there(king)
True
>>> servant = 'I do not have any cakes'
>>> num_there(servant)
False
票数 68
EN

Stack Overflow用户

发布于 2015-08-07 00:40:55

https://docs.python.org/2/library/re.html

你最好使用正则表达式。这要快得多。

import re

def f1(string):
    return any(i.isdigit() for i in string)


def f2(string):
    return re.search('\d', string)


# if you compile the regex string first, it's even faster
RE_D = re.compile('\d')
def f3(string):
    return RE_D.search(string)

# Output from iPython
# In [18]: %timeit  f1('assdfgag123')
# 1000000 loops, best of 3: 1.18 µs per loop

# In [19]: %timeit  f2('assdfgag123')
# 1000000 loops, best of 3: 923 ns per loop

# In [20]: %timeit  f3('assdfgag123')
# 1000000 loops, best of 3: 384 ns per loop
票数 30
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19859282

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档