如您所知,Python 3.6 有一个称为“格式化字符串文字”的功能。 str(obj['my_str_index'])
可以是
None
或字符串值。我已经尝试过下面的一种,但如果它是 'null'
,它不会产生 None
文本。foo = "soner test " \
f"{str(obj['my_str_index']) if str(obj['my_str_index']) is not None else 'null'}
str(None)
不是
None
,而是"None"
。因此,没有那种无用且有害的字符串化:foo = "soner test " \
f"{str(obj['my_str_index']) if obj['my_str_index'] is not None else 'null'}"
编辑:一种更清晰的方式(请注意,f 字符串中的插值会自动字符串化,因此我们根本不需要
str
):
index = obj['my_str_index']
if index is None:
index = "none"
foo = f"soner test {index}"
编辑:另一种方式,与海象(仅限 3.8+):
foo = f"soner test {'null' if (index := obj['my_str_index']) is None else index}"
foo = f"soner test {obj['my_str_index'] or 'null'}"
您不必担心
str(...)
,因为插值机制会隐式调用对象
__str__
方法(如果它没有 __format__
)。此方法的唯一警告
是,如果 foo
是错误值(
null
、obj['my_str_index']
和任何空序列)中的任何,则
None
将包含 0
。多行+{}内的表达式
foo = (
f"soner test "
f"{obj['my_str_index'] or 'null'}"
)