我正试图通过以下代码行打印一个很好的数字表:
print '{0:} {1:.5g} {2:.5g} {3:.5g} {4:.5g}'.format((i-1),a,b,p,fp)
其中 a , b , p 和 fp 是浮点数,而我恰好是一个整数。
但是我收到了这条消息:
ValueError: Unknown format code 'g' for object of type 'str'
所有提到的变量都在此函数中定义:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from sympy import *
from numpy import *
from scipy import *
def biseccion(fx,x,a,b,tolerancia,iteracionesMaximas):
i = 1
p = 0
fa = fx.subs(x,a)
while i<=iteracionesMaximas:
t = (b-a)/2
p = a+t
fp = fx.subs(x,p)
if fp == 0 or t < tolerancia:
print "Se encontró la raíz y=%f luego de %i iteraciones"%(p,(i-1))
return
i += 1
if fa * fp > 0:
a = p
else:
b = p
print '{0:} {1:.5g} {2:.5g} {3:.5g} {4:.5g}'.format((i-1),a,b,p,fp)
print 'El método falló luego de {iteraciones} iteraciones'.format(iteraciones=iteracionesMaximas)
在Python 2.7.5+版本中使用格式打印的好方法是什么?