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

函数isdigit()仅当所有字符都是数字时才返回True。我只是想看看用户是否输入了一个数字,比如“我有一只狗”之类的句子。

什么好主意吗?


当前回答

你可以这样完成:

如果a_string.isdigit (): do_this () 其他: do_that ()

https://docs.python.org/2/library/stdtypes.html#str.isdigit

使用.isdigit()还意味着在需要使用列表推导式的情况下不必求助于异常处理(try/except) (try/except在列表推导式中是不可能的)。

其他回答

你可以使用any和str.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
alp_num = [x for x in string.split() if x.isalnum() and re.search(r'\d',x) and 
re.search(r'[a-z]',x)]

print(alp_num)

这将返回所有包含字母和数字的字符串。Isalpha()返回全数字或全字符的字符串。

更简单的解决方法是

s = '1dfss3sw235fsf7s'
count = 0
temp = list(s)
for item in temp:
    if(item.isdigit()):
        count = count + 1
    else:
        pass
print count

您可以使用NLTK方法。

这将在文本中找到'1'和'One':

import nltk 

def existence_of_numeric_data(text):
    text=nltk.word_tokenize(text)
    pos = nltk.pos_tag(text)
    count = 0
    for i in range(len(pos)):
        word , pos_tag = pos[i]
        if pos_tag == 'CD':
            return True
    return False

existence_of_numeric_data('We are going out. Just five you and me.')

我很惊讶没有人使用python操作符。使用它的工作原理如下:

foo = '1dfss3sw235fsf7s'
bar = 'lorem ipsum sit dolor amet'

def contains_number(string):
    for i in range(10):
        if str(i) in list(string):
            return True
    return False

print(contains_number(foo)) #True
print(contains_number(bar)) #False

或者我们可以使用函数isdigit():

foo = '1dfss3sw235fsf7s'
bar = 'lorem ipsum sit dolor amet'

def contains_number(string):
    for i in list(string):
        if i.isdigit():
            return True
    return False

print(contains_number(foo)) #True
print(contains_number(bar)) #False

这些函数基本上只是将s转换为一个列表,并检查列表中是否包含数字。如果是,则返回True,如果不是,则返回False。