如何在使用字符串模板时将所有循环元素附加在一行中



我试图通过使用字符串模板为example.py制作模板,其中我在$ 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)))

一个问题是,由于您的代码以模式'w'打开输出文件,因此会在for循环的每次迭代中覆盖该文件。这就是为什么您只能在文件中看到最后一个。

我也不会使用string.Template来执行这些替换。只用str.format()。生成一个选择列表,并使用str.join()生成最终字符串:

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

这里selection_template使用{}作为变量替换的占位符,并使用列表推导来构造选择字符串。然后使用字符串', '作为分隔符将这些选择字符串连接在一起,并将结果字符串插入到对selection()的调用中,同样使用str.format()

在这个例子中,我使用Python的内置format string方法,它相对容易理解。如果你喜欢使用字符串模板,你可以很容易地适应它。

关键是要注意有两个单独的操作要执行:
    创建参数列表
  1. 将参数列表替换为所需输出行

我使用join的生成器表达式参数来实现必要的迭代和第1部分,然后使用简单的字符串格式化来完成第2步。

我使用字符串的format方法作为绑定函数,通过简化方法调用来简化代码。

main_format = '''
s = selection({})
'''.format
item_format = 'self.atoms["CA:"+{s}+':'+" "].select_sphere(10)'.format
items = ", ".join(item_format(s=i) for i in range(1, 4))
print(main_format(items))

最新更新