python设定字符串长度_Python-向字符串添加指定的宽度

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.

Thanks!

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'))

yields a file random_text.txt with contents

Atom word next

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.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值