在Python中添加到一行的末尾

时间:2013-03-27 17:50:32

标签: python line add

我想使用python在每行的开头和结尾添加一些字母。

我找到了各种方法来做到这一点,但是,无论哪种方法我使用我想要添加的字母然后结束总是添加到开头。

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

我使用过我在这里找到的varios方法。每个字母都添加到前面。

inserting characters at the start and end of a string

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

yourstring = "L%sLL" % yourstring

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

我在这里显然遗漏了一些东西。我该怎么办?

1 个答案:

答案 0 :(得分:7)

从文件中读取行时,python会在最后留下\n。你可以.rstrip关闭它。

yourstring = 'L{0}LL\n'.format(yourstring.rstrip('\n'))
相关问题