我发现的大多数问题都偏向于这样一个事实,即他们在数字中寻找字母,而我在我想要的无数字符串中寻找数字。 我需要输入一个字符串并检查它是否包含任何数字,以及它是否拒绝它。
函数isdigit()仅当所有字符都是数字时才返回True。我只是想看看用户是否输入了一个数字,比如“我有一只狗”之类的句子。
什么好主意吗?
我发现的大多数问题都偏向于这样一个事实,即他们在数字中寻找字母,而我在我想要的无数字符串中寻找数字。 我需要输入一个字符串并检查它是否包含任何数字,以及它是否拒绝它。
函数isdigit()仅当所有字符都是数字时才返回True。我只是想看看用户是否输入了一个数字,比如“我有一只狗”之类的句子。
什么好主意吗?
当前回答
我很惊讶没有人使用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。
其他回答
迭代器方法。它消耗所有字符,除非满足一个数字。next的第二个参数修复当迭代器为“空”时返回的默认值。在这种情况下,它被设置为False,但也“工作,因为它被强制转换为if中的布尔值。
def has_digit(string):
str_iter = iter(string)
while True:
char = next(str_iter, False)
# check if iterator is empty
if char:
if char.isdigit():
return True
else:
return False
或者只看生成器理解的第一项
def has_digit(string):
return next((True for char in string if char.isdigit()), False)
我让@zyxue的回答更明确一点:
RE_D = re.compile('\d')
def has_digits(string):
res = RE_D.search(string)
return res is not None
has_digits('asdf1')
Out: True
has_digits('asdf')
Out: False
@zyxue在答案上提出的方案中,哪个是基准测试最快的方案?
您可以像这样使用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
你可以这样完成:
如果a_string.isdigit (): do_this () 其他: do_that ()
https://docs.python.org/2/library/stdtypes.html#str.isdigit
使用.isdigit()还意味着在需要使用列表推导式的情况下不必求助于异常处理(try/except) (try/except在列表推导式中是不可能的)。
您可以使用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.')