python中的输出字符串格式

python中的输出字符串格式,python,string,formatting,Python,String,Formatting,我在输出格式化字符串时遇到错误。我正在使用Python2.6 lat = 23.456 long = 34.129 # I want to output lat and long, both occupying 8 columns in width, right justified and with 2 values beyond the decimal point site_file = open('test.site','w') site_file.write('[{:8.2f}{:8.2f

我在输出格式化字符串时遇到错误。我正在使用Python2.6

lat = 23.456
long = 34.129
# I want to output lat and long, both occupying 8 columns in width, right justified and with 2 values beyond the decimal point
site_file = open('test.site','w')
site_file.write('[{:8.2f}{:8.2f}]'.format(lat,long))
我得到以下错误: ValueError:格式为零长度的字段名

你知道我做错了什么吗


谢谢

Python2.6及更早版本要求指定格式化值的索引。以下是一个例子:

'[{} {}]'.format(a, b)    # Python 2.7 and later 
'[{0} {1}]'.format(a, b)  # Python 2.6 and earlier
我手头没有Python 2.6解释器,但我相信这是您需要的语法:

site_file.write('[{0:8.2f}{1:8.2f}]'.format(lat,long))

Python2.6和更早版本要求指定格式化值的索引。以下是一个例子:

'[{} {}]'.format(a, b)    # Python 2.7 and later 
'[{0} {1}]'.format(a, b)  # Python 2.6 and earlier
我手头没有Python 2.6解释器,但我相信这是您需要的语法:

site_file.write('[{0:8.2f}{1:8.2f}]'.format(lat,long))

long
是一个内置函数,用于转换为长整数。请不要将其用作变量名。您发布的代码适用于我-v2.7。
long
是一个内置函数,用于转换为长整数。请不要将其用作变量名。您发布的代码适用于我-v2.7。从2.6版的文档
中,每个替换字段包含位置参数的数字索引或关键字参数的名称。
从2.6版的文档
中,每个替换字段包含位置参数的数字索引,或关键字参数的名称。