[Tutor] string replacement

Luke Paireepinart rabidpoobear at gmail.com
Mon May 21 22:04:53 CEST 2007

Chandrashekar wrote:
> Hi,
> I am trying to do something like this in python. Can you please help?
> handle= open('test.txt','a')
> handle.write('''
> Testsomething$i
> something$i-test
> '''
> )
> when i write into the file, i would like to have the output like this.
> Testsomething1
> something1-test
> Testsomething2
> something2-test
> Testsomething3
> something3-test
> .......
If you want multiple lines like this, you could use list comprehensions 
and use writelines instead.
f = open("test.txt","a")
string = "Testsomething%s\nsomething%s-test\n"
n = 5
f.writelines([string % (i,i) for i in range(1,n+1)])

Note that this code produces n *2 lines of output, from 1 to n, as per 
your example output,
which is why the range goes from 1 to n+1 rather than the more common 
This saves you from having to shift each i one further in your string 
string % (i+1, i+1) would work for range(n), but should be slightly less 
Of course you'd have to profile it to be sure.
> I can perform the same using a loop. But how do i append i 
> (1,2,......n) while i am writing into the file.(I mean inside the 
> handle.write)
For each write you use a string substitution, and you do the write in a 
Or you use writelines like my above example.

Also note you're not "appending" i to the string.
You're placing it inside the string at an arbitrary position you designate.
appending means to add to the end.


More information about the Tutor mailing list