【问题标题】:Error when printing string and float打印字符串和浮点数时出错
【发布时间】:2014-11-02 18:40:53
【问题描述】:
if __name__ == "__main__":
    fptr = open(sys.argv[1], 'r')
    for line in fptr:
        list1 = []
        s = ''
        for item in re.findall(r'[\S]+', line):
            try:
                list1.append(int(item))
            except:
                s = s + item + ' '
        if not len(list1) == 0:
            avg = sum(list1) / len(list1)
            print(list1)
            print(s)
            print(avg)
            print("{0:.3f} {}".format(avg, s)) //ERROR OCCUR

这是标准输出:

[12, 14, 5, 20]
From sample set A
12.75
Traceback (most recent call last):
  File "./parse.py", line 28, in <module>
    print("{0:.3f} {}".format(avg, s))
ValueError: cannot switch from manual field specification to automatic field numbering

似乎可以单独打印字符串和平均值。但是为什么我不能一起打印呢?

【问题讨论】:

  • 因为您的字段编号不一致,正如错误消息告诉您的那样;使用"{0:.3f} {1}""{:.3f} {}",但保持一致

标签: python printing format


【解决方案1】:

Python 抱怨您对第一个格式字段进行了编号,但没有对第二个进行编号。要么把它们都编号:

print("{0:.3f} {1}".format(avg, s))
#       ^       ^

或者根本不给它们编号:

print("{:.3f} {}".format(avg, s))

但请注意,第二种解决方案仅适用于 Python 2.6 或更高版本。

【讨论】:

  • 啊..我没注意到。它现在正在工作。谢谢!
猜你喜欢
  • 2017-09-18
  • 2015-08-24
  • 2014-09-18
  • 1970-01-01
  • 1970-01-01
  • 2012-03-18
  • 1970-01-01
  • 2020-03-23
相关资源
最近更新 更多