简体   繁体   English

为什么 print 和 f-string 在不同的时间执行评估?

[英]Why do print and f-string perform evaluation at different times?

Does the evaluation of variables in print and f-string happen at different times?print和 f-string 中变量的评估是否发生在不同的时间?

I expected it to be the same output for both.我预计两者的输出相同。

def foo(x):
    x.append([5])
    return x

y, z = [1], [3]
print('y:', y, 'z:', z)
# y: [1] z: [3]

print('y:', y, 'str(y):', str(y), 'foo(y):', foo(y))  
# y: [1, [5]] str(y): [1] foo(y): [1, [5]]

print(f'z: {z} foo(z): {foo(z)} z: {z}')
# z: [3] foo(z): [3, [5]] z: [3, [5]]

Can someone explain what is happening?有人可以解释发生了什么吗?

In both cases, the expressions are evaluated left-to-right.在这两种情况下,表达式都是从左到右计算的。 In the f-string case, each is converted (with str ) immediately after evaluation, but in the case of print (which is a normal function call), all of them are evaluated (and so y is mutated) before any of them are converted to strings inside print .在 f 字符串的情况下,每个都在评估后立即转换(使用str ),但在print (这是一个正常的函数调用)的情况下,所有这些都在它们中的任何一个被评估(因此y发生变异)之前被评估在print转换为字符串。 Explicitly writing str(y) in the call to print will produce the same results.在调用print时显式写入str(y)将产生相同的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM