python - 如果条件不适用于“False”值,为什么python?
问题描述
在下面的代码中,valueis_number
为False"foo"
,但仍会is a number
为该字符串打印。为什么?我该如何解决?
def string_is_number(a_string):
pattern = re.compile(r'[0-9]+')
if pattern.search(a_string):
return("True")
else:
return("False")
for value in 42, 0.5, "foo":
the_string = str(value)
is_number = string_is_number(the_string)
print(the_string, is_number)
if is_number:
print(the_string, "is a number")
输出:
42 True
42 is a number
0.5 True
0.5 is a number
foo False
foo is a number
解决方案
返回 a bool
,而不是 a str
:
if pattern.search(a_string):
return True
else:
return False
Python 中的任何非空字符串都被认为是真的(或“真”),包括"False"
:
>>> bool("False")
True
然后,当然,您的号码检测的正则表达式有点偏离:
re.match("^\d+([.,]\d+)?$", a_string)
将是一个更严格的测试。
推荐阅读
- python - 如何知道何时在 for 循环中单独引用项目与将项目作为列表的索引
- excel - 一键插入和压缩图片的宏
- tsql - 根据子表的最大值触发更新父表
- javascript - 如何在javascript中检测转发url的来源
- swift - 如何组合来自循环的多个单独的json结果然后快速返回
- laravel - Laravel - 流或文件无法打开流:权限被拒绝
- c++ - 如何使用关联容器解决暴力破解问题?
- mysql - 如何使用 MySQL 修复从 vb.net 导出的空 .csv 文件?
- css - 添加不覆盖图像的固定粘性导航栏
- sql - 选择包含所有提到的值并排除多对多关系中的重复项的名称