使用.format()打印变量字符串和舍入的numb

2024-05-23 22:42:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我想打印如下内容:

你好7.16

这是我正在使用的代码

MyString = 'Hello'
MyFloat = 7.157777777
print "{}  ¦  {0:.2f}".format(MyString, MyFloat)

但我得到了错误:

ValueError: cannot switch from automatic field numbering to manual field specification

如果我尝试:

MyString = 'Hello'
MyFloat = 7.157777777
print "{s}  ¦  {0:.2f}".format(MyString, MyFloat)

或者str而不是s我得到错误:

KeyError: 's'

有什么办法可以打印一个带圆形浮点数的变量字符串吗?或者我应该使用类似%s的东西吗?


Tags: 代码fromformatfield内容hello错误automatic