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

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

什么好主意吗?


当前回答

您可以像这样使用str.isdigit函数使用任何函数

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

其他回答

你可以使用range和count来检查一个数字在字符串中出现了多少次:

def count_digit(a):
    sum = 0
    for i in range(10):
        sum += a.count(str(i))
    return sum

ans = count_digit("apple3rh5")
print(ans)

#This print 2

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

使用Python方法str.isalpha()。如果字符串中所有字符都是字母,并且至少有一个字符,则此函数返回True;否则返回False。

Python文档:https://docs.python.org/3/library/stdtypes.html#str.isalpha

您可以使用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.')

这也会起作用。

if any(i.isdigit() for i in s):
    print("True")