Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python中括号内包含数学表达式的字符串的format()_Python_Python 3.x_String_Format_F String - Fatal编程技术网

python中括号内包含数学表达式的字符串的format()

python中括号内包含数学表达式的字符串的format(),python,python-3.x,string,format,f-string,Python,Python 3.x,String,Format,F String,是否有方法使用.format()获得相同的结果 当我尝试这样做时,我得到了KeyError: print('something {a+2}'.format(a=10)) KeyError Traceback (most recent call last) <ipython-input-94-69f36f3c6aec> in <module> ----> 1 'something {a+2}'.for

是否有方法使用.format()获得相同的结果

当我尝试这样做时,我得到了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'

print('something{a+2}'。格式(a=10))
关键错误
回溯(最近一次呼叫最后一次)
在里面
---->1'某物{a+2}'。格式(a=10)
KeyError:'a+2'
Python 3.8新功能(Walrus)

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的期望)

print('something{a}.format(a=10+2)
,只需像这样在外部执行操作?
print('something{}.format(a+2))
您似乎有特定的想法。Netwave,您的8次编辑(和删除的答案)都没有到目前为止,我一直在努力…@NicolasGervais,是的,我没有正确地阅读这个问题。f字串的工作方式与格式不同。使用f字串可以作为第一个示例,但使用格式时,您需要执行与上面评论中的示例类似的操作。OP询问更多关于
格式
,而较少关于f字串。
f{a+2}
适用于f字串。虽然在3.8中使用walrus,但这个例子是一个有趣的想法。嗯!我错过了
a = 10
print(f'something {(result:=a+2)}')
print(f'something {(a+2)}')
print(f'something {a + 2}')
print('something {a}'.format(a=10 + 2))
print('something {}'.format(a+2))