2011-12-10 29 views
3

我想寫一個字符串到一個文件,但我想有一個指定的長度,例如,在文本文件中,我想寫「Atom」,我希望它有從第1-6列開始的指定長度,以及下一個短語/單詞,從第7-11列開始,接下來從13-16開始,等等...我想寫入文本文件,例如random_text.txt,請幫助。Python-給字符串添加一個指定的寬度

謝謝!

基本上,我爲什麼需要它:

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 
+0

你在找什麼東西像[textwrap](http://docs.python.org/library/textwrap.html)? – miku

回答

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

+0

你會怎麼做,原子的寬度是1-6列,單詞是7-11,接下來是13-16? – hihey

+1

通過指定寬度,可以間接安排下一列開始的位置。例如,通過指定col [0]具有寬度6,下一列將從位置7開始。但是,您必須小心'len(col [0])<= 6',否則格式化的字符串將會跑到下一列。 – unutbu

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

這將截斷stringwidth如果有必要的,因爲你不能真正指定格式字符串中的最大寬度,只是最小寬度,該字段將被填充到。

0

使用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 
相關問題