Python 和 F-Strings 解释 [英] Python and F-Strings explanation
问题描述
在后面的 f-string 中,
print("它的羊毛像{}一样白.".format('snow'))
'snow'
是一个变量吗?我对它究竟会被判断为什么感到困惑.
不,'snow'
是一个字符串字面量,一个产生字符串值的表达式.snow
将是一个变量名(注意没有引号).
比较:
<预><代码>>>>'雪''雪'>>>雪回溯(最近一次调用最后一次):文件<stdin>",第 1 行,位于 <module>NameError:未定义名称雪">>>雪 = 42>>>雪42>>>雪 = '雪'>>>雪'雪'变量 snow 一开始还没有赋值,所以尝试使用它会导致异常.然后我为名称分配了一个整数,然后是值为 'snow'
的字符串.
用另一个字符串文字格式化一个字符串文字是毫无意义的.您通常会使用实际变量,因此您可以改变产生的输出:
compared_to = 'snow'打印(它的羊毛是白色的{}.".format(compared_to))
此外,这不是 f
字符串.f
字符串文字以 f
字符开头.您在这里拥有的是一个常规的、普通的字符串文字,以及对 str.format()
方法.以下是使用 f 字符串的等效表达式:
print(f"它的羊毛白得像{'雪'}.")
参见 python-3.6 中带有 'f' 前缀的字符串 有关实际 f 字符串的更多信息.
In the follow f-string,
print("It's fleece was white as {}.".format('snow'))
Is 'snow'
a variable? I am confused with what exactly it would be judged as.
No, 'snow'
is a string literal, an expression that produces a string value. snow
would be a variable name (note the lack of quotes).
Compare:
>>> 'snow'
'snow'
>>> snow
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'snow' is not defined
>>> snow = 42
>>> snow
42
>>> snow = 'snow'
>>> snow
'snow'
The variable snow at first wasn't yet assigned to, so trying to use it caused an exception. I then assigned an integer to the name, and then the string with value 'snow'
.
Formatting a string literal with another string literal is pretty meaningless. You'd normally use an actual variable, so you can vary the output produced:
compared_to = 'snow'
print("It's fleece was white as {}.".format(compared_to))
Also, that's not an f
string. An f
string literal starts with a f
character. What you have here is a regular, run-of-the-mill string literal, and a call to the str.format()
method. The following is the equivalent expression using an f-string:
print(f"It's fleece was white as {'snow'}.")
See String with 'f' prefix in python-3.6 for more information on actual f-strings.
这篇关于Python 和 F-Strings 解释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!