简体   繁体   中英

format() on a string with a math expression inside brackets in python

Is there a way to get the same result using.format()?

a = 10
print(f'something {a+2}')
something 12

When I try to do it like this I get KeyError:

print('something {a+2}'.format(a=10))
KeyError                                  
Traceback (most recent call last)
<ipython-input-94-69f36f3c6aec> in <module>
----> 1 'something {a+2}'.format(a=10)

KeyError: 'a+2'

Python 3.8 new feature (Walrus)

a = 10
print(f'something {(result:=a+2)}')

Python 3.7

print(f'something {(a+2)}')
print(f'something {a + 2}')
print('something {a}'.format(a=10 + 2))
print('something {}'.format(a+2))

Updated all above options (Just to match OP's expectations)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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