简体   繁体   English

在python中输出字符串格式

[英]Output string formatting in python

I am encountering an error in outputting a formatted string. 我在输出格式化字符串时遇到错误。 I am using Python2.6 我正在使用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))

I get the following error: ValueError: zero length field name in format 我收到以下错误:ValueError:格式的零长度字段名称

Any ideas on what I am doing wrong? 关于我在做什么错的任何想法吗?

thanks! 谢谢!

Python 2.6 and earlier require that you specify the index of the formatted values. Python 2.6和更早版本要求您指定格式值的索引。 Here is an example: 这是一个例子:

'[{} {}]'.format(a, b)    # Python 2.7 and later 
'[{0} {1}]'.format(a, b)  # Python 2.6 and earlier

I do not have a Python 2.6 interpreter handy, but I believe this is the syntax that you need: 我没有方便的Python 2.6解释器,但是我相信这是您需要的语法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM