检查字符串是否为实数
有没有一种快速方法来查找字符串是否为实数,而不是一次读取一个字符并对每个字符执行 isdigit()
?我希望能够测试浮点数,例如 0.03001
。
Is there a quick way to find if a string is a real number, short of reading it a character at a time and doing isdigit()
on each character? I want to be able to test floating point numbers, for example 0.03001
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
如果您将浮点数表示为实数,则这应该可以工作:
请注意,这将在内部仍然循环您的字符串,但这是不可避免的。
If you mean an float as a real number this should work:
Note that this will internally still loop your string, but this is inevitable.
您可以这样做:
如果您想要一个浮点数,请将
int
替换为float
(感谢 @cobbal)。You can do that:
If you want a float number, replace
int
byfloat
(thanks to @cobbal).还有另一种使用正则表达式的方法:
There is also another way using regular expression:
有一个更精确的实数正则表达式:
并且对此正则表达式进行一些检查:
There is a more precise regexp of the real numbers:
And some check for this regexp:
验证实数的方法:
Method to verify real number:
定义一个函数来执行此操作是正确的方法,尽管遗憾的是 Python 尚未提供这样的函数。
我不喜欢使用 try ...除了这一点,因为我被灌输了“例外是针对特殊情况的”,而不是针对控制流的。
一行解决方案(如果您需要它,尽管效率较低,除了正则表达式答案)是
如果您将遇到写为
1.
或.01< /code>,然后只需添加长度检查
Defining a function to do this is the right approach, although it's a shame that Python does not already provide such a function.
I'm not a fan of using try ... except for this, because it was drilled into me that "exceptions are for exceptional circumstances", and not for control flow.
A one-line solution (if you ever want it, although it is less efficient, except for the regex answers) is
If you are going to encounter decimals written as
1.
or.01
, then simply add a length check如果你想检查整数和浮点数,你可以看看这个
if you wanna check both integer and float numbers, you can check this out