检查字符串中的数字 - 没有循环且没有库[重复]

问题描述 投票:-2回答:2

这个问题在这里已有答案:

我想要一个字符串,例如我想键入'我有2只狗',我希望shell返回True(函数会这样做),如果字符串中显示了一个数字。我发现如果不使用任何循环并且没有任何're'或'string'库就很难编码。

有什么帮助吗?

例:

input: "I own 23 dogs"
output: True

input: "I own one dog"
output: False
python
2个回答
1
投票

列表理解可以帮助您:

def is_digit(string):
    return any(c.isdigit() for c in string)

print(is_digit("I own 23 dogs"))
print(is_digit("I own one dog"))

输出:

True
False

1
投票
>>> a = "I own 23 dogs"
>>> print(bool([i for i in a if i.isdigit()]))
True

>>> b = "I own some dogs"
>>> print(bool([i for i in b if i.isdigit()]))
False

然而,更好的解决方案是使用any并使用生成器代替列表以获得更好的性能(就像@Alderven解决方案一样):

>>> a = "I own 23 dogs"
>>> any(i.isdigit() for i in a)
True
© www.soinside.com 2019 - 2024. All rights reserved.