我发现的大多数问题都偏向于这样一个事实,即他们在数字中寻找字母,而我在我想要的无数字符串中寻找数字。 我需要输入一个字符串并检查它是否包含任何数字,以及它是否拒绝它。
函数isdigit()仅当所有字符都是数字时才返回True。我只是想看看用户是否输入了一个数字,比如“我有一只狗”之类的句子。
什么好主意吗?
我发现的大多数问题都偏向于这样一个事实,即他们在数字中寻找字母,而我在我想要的无数字符串中寻找数字。 我需要输入一个字符串并检查它是否包含任何数字,以及它是否拒绝它。
函数isdigit()仅当所有字符都是数字时才返回True。我只是想看看用户是否输入了一个数字,比如“我有一只狗”之类的句子。
什么好主意吗?
当前回答
你可以使用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
其他回答
你可以使用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
使用Python方法str.isalpha()。如果字符串中所有字符都是字母,并且至少有一个字符,则此函数返回True;否则返回False。
Python文档:https://docs.python.org/3/library/stdtypes.html#str.isalpha
此外,您可以使用regex findall。这是一个更通用的解决方案,因为它增加了对数字长度的更多控制。在需要最小长度的数字的情况下,这可能会很有帮助。
s = '67389kjsdk'
contains_digit = len(re.findall('\d+', s)) > 0
您可以像这样使用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
您可以使用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.')