0

With f-string I can do like this:

a = 10
f'a equals {a}'  # 'a equals 10'
f'b equals {a - 1}'  # 'b equals 9'

but when using .format I cannot do any operation on the variable:

'b equals {a - 1}'.format(dict(a=10))  # KeyError: 'a  - 1'

The error message is clear - the format function treats everything in the {} as an argument name. Can I circumvent that somehow?

I cannot use the f-string, because the message is prepared before values of the variables are known.

EDIT: Ok, it seems that it can not be possible - it would work as an implicit eval which would be very unsafe.

hans
  • 1,043
  • 12
  • 33

1 Answers1

1

When using format, the {} are a place holder for an expression. Do the arithmetic in the format argument, not in the place holder.

str = "a = {}"
a = 10
stra = str.format(a-1)
print(stra)
>> a = 9
Triceratops
  • 741
  • 1
  • 6
  • 15