如何在Python中引用空对象?
当前回答
用f来解决这个问题。
year=None
year_val= 'null' if year is None else str(year)
print(f'{year_val}')
null
其他回答
Null是一个特殊的对象类型,比如:
>>>type(None)
<class 'NoneType'>
你可以检查一个对象是否在类'NoneType'中:
>>>variable = None
>>>variable is None
True
更多信息可以在Python文档中找到
上面的答案只会为None的结果为True,但存在float('nan')这样的东西。你可以使用pandas isnull:
>>> import pandas as pd
>>> pd.isnull(None)
True
>>> pd.isnull(float('nan'))
True
>>> pd.isnull('abc')
False
>>>
或者没有熊猫:
>>> a = float('nan')
>>> (a != a) or (a == None)
True
>>> a = None
>>> (a != a) or (a == None)
True
>>>
这样做的原因是float('nan') != float('nan'):
>>> float('nan') == float('nan')
False
>>> float('nan') != float('nan')
True
>>>
根据真值测试,'None'直接测试为FALSE,所以最简单的表达式就足够了:
if not foo:
在Python中,“null”对象是单例None。
要检查某个值是否为None,使用is标识符:
if foo is None:
...
在Python中处理“空”元素的简单函数:
代码:
def is_empty(element) -> bool:
"""
Function to check if input `element` is empty.
Other than some special exclusions and inclusions,
this function returns boolean result of Falsy check.
"""
if (isinstance(element, int) or isinstance(element, float)) and element == 0:
# Exclude 0 and 0.0 from the Falsy set.
return False
elif isinstance(element, str) and len(element.strip()) == 0:
# Include string with one or more empty space(s) into Falsy set.
return True
elif isinstance(element, bool):
# Exclude False from the Falsy set.
return False
else:
# Falsy check.
return False if element else True
测试:
print("Is empty?\n")
print('"" -> ', is_empty(""))
print('" " -> ', is_empty(" "))
print('"A" -> ', is_empty("A"))
print('"a" -> ', is_empty("a"))
print('"0" -> ', is_empty("0"))
print("0 -> ", is_empty(0))
print("0.0 -> ", is_empty(0.0))
print("[] -> ", is_empty([]))
print("{} -> ", is_empty({}))
print("() -> ", is_empty(()))
print("[1, 2] -> ", is_empty([1, 2]))
print("(3, 5) -> ", is_empty((3, 5)))
print('{"a": 1} -> ', is_empty({"a": 1}))
print("None -> ", is_empty(None))
print("True -> ", is_empty(True))
print("False -> ", is_empty(False))
print("NaN -> ", is_empty(float("nan")))
print("range(0) -> ", is_empty(range(0)))
输出:
Is empty?
"" -> True
" " -> True
"A" -> False
"a" -> False
"0" -> False
0 -> False
0.0 -> False
[] -> True
{} -> True
() -> True
[1, 2] -> False
(3, 5) -> False
{"a": 1} -> False
None -> True
True -> False
False -> False
NaN -> False
range(0) -> True
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if
- 如何在Python中获得所有直接子目录