简体   繁体   中英

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?

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'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM