检查字符串是否包含数字 [英] Check if a string contains a number

查看:88
本文介绍了检查字符串是否包含数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现的大多数问题都偏向于他们正在寻找数字中的字母,而我正在寻找我希望成为无数字字符串中的数字.我需要输入一个字符串并检查它是否包含任何数字以及是否拒绝它.

函数 isdigit() 只有在所有字符都是数字时才返回 True.我只是想看看用户是否输入了一个数字,比如I own 1 dog"之类的句子.

有什么想法吗?

解决方案

您可以使用 any 函数,带有 str.isdigit 函数,像这样

<预><代码>>>>def hasNumbers(inputString):... return any(char.isdigit() for char in inputString)...>>>hasNumbers("我拥有 1 只狗")真的>>>hasNumbers("我没有养狗")错误的

或者你可以使用正则表达式,就像这样

<预><代码>>>>进口重新>>>def hasNumbers(inputString):... return bool(re.search(r'\d', inputString))...>>>hasNumbers("我拥有 1 只狗")真的>>>hasNumbers("我没有养狗")错误的

Most of the questions I've found are biased on the fact they're looking for letters in their numbers, whereas I'm looking for numbers in what I'd like to be a numberless string. I need to enter a string and check to see if it contains any numbers and if it does reject it.

The function isdigit() only returns True if ALL of the characters are numbers. I just want to see if the user has entered a number so a sentence like "I own 1 dog" or something.

Any ideas?

解决方案

You can use any function, with the str.isdigit function, like this

>>> def hasNumbers(inputString):
...     return any(char.isdigit() for char in inputString)
... 
>>> hasNumbers("I own 1 dog")
True
>>> hasNumbers("I own no dog")
False

Alternatively you can use a Regular Expression, like this

>>> import re
>>> def hasNumbers(inputString):
...     return bool(re.search(r'\d', inputString))
... 
>>> hasNumbers("I own 1 dog")
True
>>> hasNumbers("I own no dog")
False

这篇关于检查字符串是否包含数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆