【问题标题】:How to append all the loop elements in single line while using string Template?使用字符串模板时如何在单行中附加所有循环元素?
【发布时间】: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


    【解决方案1】:

    一个问题是您的代码,因为它以'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()

    【讨论】:

    • 非常感谢 mhawke
    【解决方案2】:

    在这个例子中我使用了Python内置的format字符串方法,这个方法比较容易理解。如果您更喜欢使用字符串模板,您可以轻松适应它。

    诀窍是观察有两个单独的操作要执行:

    1. 创建参数列表
    2. 在所需的输出行中替换参数列表

    我使用 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))
    

    【讨论】:

      猜你喜欢
      • 2015-11-06
      • 2016-11-06
      • 2020-09-29
      • 1970-01-01
      • 2020-09-26
      • 2017-07-10
      • 2019-07-16
      • 2014-08-18
      • 1970-01-01
      相关资源
      最近更新 更多