Search code examples
pythonprintingpython-3.6incrementf-string

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


Example in C programming:

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

In Python even if I use f - string i can't able to use it directly!

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

it's not working


Solution

  • Yes, kind of, using an assignment expression (:=):

    print(a := a + 1)
    

    I wouldn't do this though. It needlessly convolutes your code. Just have a separate a += 1 line for the sake of clarity.

    Though, this only works in Python 3.8+. If you're on an earlier version of Python, no, there is no way of doing this outside of a creative hack like:

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

    := is the only sane way to reassign a variable in a context that expects an expression.