如何在Python中引用空对象?
当前回答
用f来解决这个问题。
year=None
year_val= 'null' if year is None else str(year)
print(f'{year_val}')
null
其他回答
在Python中,“null”对象是单例None。
要检查某个值是否为None,使用is标识符:
if foo is None:
...
根据真值测试,'None'直接测试为FALSE,所以最简单的表达式就足够了:
if not foo:
它不像其他语言那样叫null,而是None。这个对象总是只有一个实例,所以如果需要,可以检查x is None(标识比较)是否相等,而不是x == 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
用f来解决这个问题。
year=None
year_val= 'null' if year is None else str(year)
print(f'{year_val}')
null
推荐文章
- 如何排序mongodb与pymongo
- 不可变与可变类型
- 列表是线程安全的吗?
- getActivity()在Fragment函数中返回null
- 操作系统。makdirs在我的路径上不理解“~”
- 如何在Django模板中获得我的网站的域名?
- 在django Forms中定义css类
- 如何在Python中scp ?
- Numpy Max vs amax vs maximum
- 我应该在.gitignore文件中添加Django迁移文件吗?
- 每n行有熊猫
- 在JavaScript中根据键值查找和删除数组中的对象
- 实例属性attribute_name定义在__init__之外
- 如何获取在Python中捕获的异常的名称?
- 第一次出现的值大于现有值的Numpy