在Python中添加到行尾

2024-09-27 09:26:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用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()

我用了我在这里找到的各种方法。每一个字母都加在前面。在

inserting characters at the start and end of a string

^{pr2}$

或者

yourstring = "L%sLL" % yourstring

或者

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

很明显我遗漏了一些东西。我能做什么?在


Tags: 方法inforcloseinputoutput结尾字母
1条回答
网友
1楼 · 发布于 2024-09-27 09:26:31

从文件中读取行时,python将\n留在末尾。但是你可以.rstrip关掉它。在

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

相关问题 更多 >

    热门问题