在Python括号内带有数学表达式的字符串上的format() [英] format() on a string with a math expression inside brackets in python

查看:74
本文介绍了在Python括号内带有数学表达式的字符串上的format()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用.format()获得相同的结果?

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

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

当我尝试这样做时,出现KeyError:

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的新功能(海象)

Python 3.8 new feature (Walrus)

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))

更新了以上所有选项(仅符合OP的期望)

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

这篇关于在Python括号内带有数学表达式的字符串上的format()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆