Python-向字符串添加指定的宽度 [英] Python- Adding a specified width to strings
问题描述
我想向文件中写入一个字符串,但是我希望具有指定的长度,例如,在文本文件中,我要写入"Atom",我希望它从1-6列开始具有指定的长度,以及下一个短语/单词,分别位于第7-11列,下一个13-16等,等等...我想写一个文本文件,说是random_text.txt,请帮忙.
I want to write a string to a file but I want to have a specified length, for example, in the text file, I want to write "Atom", I want it to have a specified length from column 1 - 6, and the next phrase/word, from column 7-11, next from 13-16, and etc... I would want to write to a text file say, random_text.txt, please help.
谢谢!
基本上,为什么我需要它:
Basically, why I need it:
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
推荐答案
In Python2.6 or later, you could use the str.format method:
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}
可以对字符串进行右对齐",并且有
The number following the colon indicate the width. For example, {0:6}
formats the 0-th argument, 'Atom'
, into a string with a width of 6. The string could be "right-justified" by using the format {0:>6}
, and there are other options as well.
这篇关于Python-向字符串添加指定的宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!