Constantin
Constantin

Reputation: 35

Adding to the end of a line in Python

I want to add some letters to the beginning and end of each line using python.

I found various methods of doing this, however, whichever method I use the letters I want to add to then end are always added to the beginning.

input = open("input_file",'r')
output = open("output_file",'w')

for line in input:
    newline = "A" + line + "B"
    output.write(newline)
input.close()
output.close()

I have used varios methods I found here. With each one of them both letters are added to the front.

inserting characters at the start and end of a string

''.join(('L','yourstring','LL'))

or

yourstring = "L%sLL" % yourstring

or

yourstring = "L{0}LL".format(yourstring)

I'm clearly missing something here. What can I do?

Upvotes: 3

Views: 1133

Answers (1)

mgilson
mgilson

Reputation: 309929

When reading lines from a file, python leaves the \n on the end. You could .rstrip it off however.

yourstring = 'L{0}LL\n'.format(yourstring.rstrip('\n'))

Upvotes: 7

Related Questions