简体   繁体   English

format() 在 python 中括号内带有数学表达式的字符串上

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

Is there a way to get the same result using.format()?有没有办法使用.format() 获得相同的结果?

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

When I try to do it like this I get KeyError:当我尝试这样做时,我得到 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) Python 3.8 新功能(海象)

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

Python 3.7 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)更新了上述所有选项(只是为了符合 OP 的期望)

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

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