Python-为字符串添加指定的宽度

时间:2011-12-10 19:48:22

标签: python file textwrapping

我想在一个文件中写一个字符串,但我希望有一个指定的长度,例如,在文本文件中,我想写“Atom”,我希望它有一个指定的长度,从第1 - 6列开始,以及下一个短语/单词,从第7-11行开始,接下来是13-16,等等...我想写一个文本文件说,random_text.txt,请帮忙。

谢谢!

基本上,我为什么需要它:

Column 1-6 Record Name
Column 7-11 Serial Number
Column 13-16 ATOM name/Type
Column 17 Alternate Location Indicator
Column 18-20 Residue Name
Column 22 Chainidentifier 
Column 23-26 Residue sequence number
Column 27 Code for insertion fo residues
Column 31-38 X-value
Column 39-46 Y-value
Column 47-54 Z-Value
Column 55-60 Occupency
Column 61-66 Temperature (Default 0.0)
Column 73-76 Segment identifier
Column 77-78 Element Symbol
Column 79-80 Charge on atom

3 个答案:

答案 0 :(得分:8)

在Python2.6或更高版本中,您可以使用str.format方法:

with open('random_text.txt', 'w') as f:
    f.write('{0:6}{1:6}{2:4}'.format('Atom','word','next'))

生成包含内容

的文件random_text.txt
Atom  word  next

冒号后面的数字表示宽度。例如,{0:6}将第0个参数'Atom'格式化为宽度为6的字符串。字符串可以使用格式{0:>6}“右对齐”,并且有other options as well

答案 1 :(得分:4)

string = "atom"
width = 6
field = "{0:<{1}}".format(string[:width], width)

如果需要,这会将string截断为width,因为您无法实际指定格式字符串中的最大宽度,只是字段将被填充到的最小宽度。

答案 2 :(得分:2)

使用str.format,定义字段宽度(:<width>)并展开您的数据(*<list>)。

>>> columns = ['aaaa', 'bbbbbb', 'ccc']
>>> print '{:4}{:6}{:3}'.format(*columns)

此外,您可以滥用精度.8来修剪字符串字段。前8个设置最小字段宽度。

>>> print '{:8.8}'.format('Too long for this field')
Too long