问题描述
我想知道为什么 f'{None}_some_string'
不抛出错误?
以下是重现问题的一些示例:
s1 = None # <class 'nonetype'>
s2 = 'real_string' # <class 'str'>
s1 + s2 # TypeError: unsupported operand type(s) for +: 'nonetype' and 'str
f'{s1}_bla'
'None_bla'
f'{s2}_bla'
'real_string_bla'
当 f'{s}_some_string'
为 s
时,是否可以使 None
之类的表达式抛出错误?
解决方法
默认情况下,f-string 应用 str()
(字符串)函数。
f'{None}_some_string'
相当于...
f'{str(None)}_some_string}'