【发布时间】:2016-06-28 11:40:26
【问题描述】:
我尝试使用字符串模板为 example.py 制作一个模板,其中我将每个 for 循环元素替换为 $i ["CA:"+$i+':'+" " ]。它部分有效,但仅替换最后一个元素。
但是,我想以某种格式将所有值附加到单行中。
例如:
我当前的脚本执行如下:
for i in range(1,4):
#It takes each "i" elements and substituting only the last element
str='''s=selection( self.atoms["CA:"+$i+':'+" "].select_sphere(10) )
我得到如下:
s=selection( self.atoms["CA:"+3+':'+" "].select_sphere(10) )
什么,我期待如下:
s=selection ( self.atoms["CA:"+1+':'+" "].select_sphere(10),self.atoms["CA:"+2+':'+" "].select_sphere(10),self.atoms["CA:"+3+':'+" "].select_sphere(10) )
我的脚本:
import os
from string import Template
for i in range(1,4):
str='''
s=selection( self.atoms["CA:"+$i+':'+" "].select_sphere(10) )
'''
str=Template(str)
file = open(os.getcwd() + '/' + 'example.py', 'w')
file.write(str.substitute(i=i))
file.close()
我使用这两个脚本来获得我想要的输出:
import os
from string import Template
a=[]
for i in range(1,4):
a.append(''.join("self.atoms["+ "'CA:' "+str(i)+""':'+" "+"]"+".select_sphere(10)"))
str='''s=selection( $a ).by_residue()'''
str=Template(str)
file = open(os.getcwd() + '/' + 'example.py', 'w')
file.write(str.substitute(a=a))
with open('example.py', 'w') as outfile:
selection_template = '''self.atoms["CA:"+{}+':'+" "].select_sphere(10)'''
selections = [selection_template.format(i) for i in range(1, 4)]
outfile.write('s = selection({})\n'.format(', '.join(selections)))
【问题讨论】:
标签: python string python-2.7 append stringtemplate