如何在python中定义列范围

时间:2013-09-24 12:31:46

标签: python math numpy

我写了一个python程序,我得到了像这样的输出

ATOM         OW  HOH             6.016 23.68 63.478        
ATOM         OW  HOH             11.522 24.153 61.585   
ATOM         OW  HOH             10.849 26.167 62.012  
ATOM         OW  HOH             6.774 23.656 63.543  
ATOM         OW  HOH             8.255 22.341 66.519  
ATOM         OW  HOH             8.891 23.732 67.313  
ATOM         OW  HOH             9.193 25.411 67.03  
ATOM         OW  HOH             8.208 25.255 67.332  

但我希望输出像

ATOM         OW  HOH              6.016 23.68  63.478        
ATOM         OW  HOH             11.522 24.153 61.585   
ATOM         OW  HOH             10.849 26.167 62.012  
ATOM         OW  HOH              6.774 23.656 63.543  
ATOM         OW  HOH              8.255 22.341 66.519  
ATOM         OW  HOH              8.891 23.732 67.313  
ATOM         OW  HOH              9.193 25.411 67.03  
ATOM         OW  HOH              8.208 25.255 67.332  

任何帮助都是值得的。

outfile2 = open('randomcoord.pdb', 'w')
hetam = 'ATOM         OW  HOH            ' + ' ' + str(round(pacord[0], 3)) + ' ' + str(round(pacord[1], 3)) + ' ' + str(round(pacord[2], 3))

            outfile2.write(hetam)

            outfile2.write('\n')
outfile2.close()

3 个答案:

答案 0 :(得分:3)

使用%格式化运算符,让它执行舍入和填充:

with open('randomcoord.pdb', 'w') as f:
    f.write('ATOM         OW  HOH             %6.3f %6.3f %6.3f\n'
            % (pacord[0], pacord[1], pacord[2]))

答案 1 :(得分:1)

定义你想要的字符串的长度,假设它是6(点之前的两个地方,之后的三个,以及点本身)。

N = 6

然后,不要像你那样打印,写下:

str(round(pacord[0], 3)).rjust(N,' ')

答案 2 :(得分:1)

与user4815162342类似,但使用现代格式化工具:

hetam = 'ATOM         OW  HOH            {:6.3f} {:6.3f} {:6.3f}\n'.format(*pacord)

请注意,如果您将写入文件,我建议使用print

with open('randomcoord.pdb', 'w') as outfile2:
    print('ATOM         OW  HOH            {:6.3f} {:6.3f} {:6.3f}'.format(*pacord), file=outfile2)