Don't print your newlines, write them to the file instead:
for line in input_f :
output_f.write("\n+ ")
for y in enumerate([x[0] for x in enumerate(line) if x[1]=='a']):
a = ("%d:%d" % (y[0]+1,y[1]+1))
output_f.write(a + " ")
You could use some tuple unpacking to make it a little clearer what you are enumerating, and you can drop the [..]
list comprehension and use a generator expression instead (saves some memory and processing):
for i, pos in enumerate((pos for pos, char in enumerate(line, 1) if char == 'a'), 1):
output_f.write('%d:%d ' % (i, pos))
I also gave the enumerate()
function a second argument, the start value, so you don't have to + 1
each number, and added the space in the file output in the string formatting.
You would normally write the newline after writing a line; and if you wanted a counter per line, add another enumerate::
for count, line in enumerate(input_f, 1):
output_f.write("%d+ " % count)
for i, pos in enumerate((pos for pos, char in enumerate(line, 1) if char == 'a'), 1):
output_f.write('%d:%d ' % (i, pos))
output_f.write('\n')
or, by using str.join()
you can create a whole line in one go, using formatting to include the prefix and newline in one formatting operation:
for count, line in enumerate(input_f, 1):
positions = (pos for pos, char in enumerate(line, 1) if char == 'a')
line = ' '.join(['%d:%d' % (i, pos) for i, pos in enumerate(positions, 1)])
output_f.write("%d+ %s\n" % (count, line))
which neatly avoids a trailing space as well.