有没有办法像我们在 c 中那样直接在 python 的 print 语句中使用递增和递减运算符

Is thera a way to use increment and decrement operators directly inside the print statement in python like we do in c

C 编程示例:

int a=5;
printf("a : %d",++a);

在Python中即使我使用f-string我也不能直接使用它!

print(f'a : {++a}')

没用

是的,有点,使用赋值表达式 (:=):

print(a := a + 1)

虽然我不会这样做。它不必要地使您的代码复杂化。为了清楚起见,只需要一个单独的 a += 1 行。

不过,这只适用于 Python 3.8+。如果您使用的是 Python 的早期版本,不,除了像这样的创意黑客之外,没有其他方法可以做到这一点:

print((exec("a += 1"), a)[1])  # DEFINATELY DO NOT USE THIS!

:= 是在需要表达式的上下文中重新分配变量的唯一合理方法。