python - How to append all the loop elements in single line while using string Template? -
i have tried make template example.py using string template substitute each loop elements in $i ["ca:"+$i+':'+" "]. partially works substituting last element.
but, want append values in single line format .
for example:
what current script doing follows:
for in range(1,4): #it takes each "i" elements , substituting last element str='''s=selection( self.atoms["ca:"+$i+':'+" "].select_sphere(10) )
what getting follows:
s=selection( self.atoms["ca:"+3+':'+" "].select_sphere(10) )
what, expecting follows:
s=selection ( self.atoms["ca:"+1+':'+" "].select_sphere(10),self.atoms["ca:"+2+':'+" "].select_sphere(10),self.atoms["ca:"+3+':'+" "].select_sphere(10) )
my script:
import os string import template 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()
i use 2 scripts desired output:
import os string import template a=[] 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)) open('example.py', 'w') outfile: selection_template = '''self.atoms["ca:"+{}+':'+" "].select_sphere(10)''' selections = [selection_template.format(i) in range(1, 4)] outfile.write('s = selection({})\n'.format(', '.join(selections)))
one problem code, because opens output file mode 'w'
, overwrites file on each iteration of loop. why see last 1 in file.
also wouldn't use string.template
perform these substitutions. use str.format()
. generate list of selections , use str.join()
produce final string:
with open('example.py', 'w') outfile: selection_template = 'self.atoms["ca:"+{}+":"+" "].select_sphere(10)' selections = [selection_template.format(i) in range(1, 4)] outfile.write('s = selection({})\n'.format(', '.join(selections)))
here selection_template
uses {}
placeholder variable substitution , list comprehension used construct selection strings. these selection strings joined using string ', '
separator , resulting string inserted call selection()
, again using str.format()
.
Comments
Post a Comment