在 Python 中检查字符串中的数字
如何在Python中检查字符串是否包含数字?
我有一个要转换为浮点数的变量,但我想制作 if 语句,仅当它仅包含数字时才将其转换为浮点数。
How to check if string contains numbers in Python?
I have a variable which I am convert to float, but I want to make if statement, to convert it to float only if it contains only numbers.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
只需转换它并在失败时捕获异常即可。
Just convert it and catch the exception if it fails.
我会使用 try- except 块来确定它是否是一个数字。这样,如果 s 是一个数字,则转换成功,如果不是,您将捕获 ValueError,这样您的程序就不会中断。
I would use a try-except block to determine if it is a number. That way if s is a number the cast is successful, and if it isn't you catch the ValueError so your program doesn't break.
您还可以从字符串中提取数字。
然后将它们转换为浮点数。
You could also extract numbers from a string.
and then convert them to float.
为什么不使用内置的
.isdigit()
来实现此目的。紧凑、无 try 语句且速度超快:在考虑 Python 中的错误处理时,我相信尤达大师曾说过:“没有 try。做或不做。”
Why not the built-in
.isdigit()
for this. Compact, notry
statements, and super fast:When considering error handling in Python, I believe it was Master Yoda who said, "There is no try. Do or do not."
迈克尔·巴伯的答案对于速度来说是最好的,因为没有不必要的逻辑。如果由于某种原因您发现需要进行更精细的评估,您可以使用 Python 标准库的正则表达式模块。例如,如果您决定想要获得您所描述的数字,但有想要分层的其他标准,这将对您有所帮助。
正则表达式表示,'查找最多以一位小数开头的内容('^' 表示仅在行开头,'?' 表示最多一位;小数点用 '\' 转义,因此不会有其特殊的正则表达式含义为“任何字符”)并且具有任意数量的数字。祝 Python 好运!
Michael Barber's answer will be best for speed since there's no unnecessary logic. If for some reason you find you need to make a more granular assessment, you could use the Python standard library's regular expression module. This would help you if you decided, for example, that you wanted to get a number like you described but had additional criteria you wanted to layer on.
The regular expression says, 'find something that starts with up to one decimal ('^' means only at beginning of line and the '?' means up to one; the decimal is escaped with a '\' so it won't have its special regular expression meaning of 'any character') and has any number of digits. Good luck with Python!