Count and replacing strings a texfile
Greg Jorgensen
gregj at pobox.com
Thu Jan 25 14:18:46 EST 2001
In article <94p56k022uc at news2.newsguy.com>,
"Alex Martelli" <aleaxit at yahoo.com> wrote:
> ...
> It's a good maxim, but collecting the pieces in a list
> and joining them up at the end is no harder than joining
> them up as you go...
You are right. Here's my original code with your simple change and a
typo corrected:
===
# read all text from the file
f = open(filename, "r")
s = f.read()
f.close()
# split text into a list at every occurence of %id%
t = s.split("%id%")
n = len(t) # number of list elements
r = [t[0]] # start with first element in list
# iterate over list, inserting counter between elements
for i in range(1,n):
r.append(str(i) + t[i])
result = ''.join(r)
print "%s occurences replaced" % (n-1)
print result
===
--
Greg Jorgensen
Portland, Oregon, USA
gregj at pobox.com
Sent via Deja.com
http://www.deja.com/
More information about the Python-list
mailing list