0

我写了一个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()
4

3 回答 3

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]))
于 2013-09-24T12:51:08.763 回答
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)
于 2013-09-24T12:56:25.917 回答
1

定义您想要的字符串的长度,假设它是 6(点之前的两个位置,之后的三个位置和点本身)。

N = 6

然后,不要像你一样打印,而是写:

str(round(pacord[0], 3)).rjust(N,' ')
于 2013-09-24T12:38:56.760 回答