【问题标题】:Adding to the end of a line in Python在 Python 中添加到行尾
【发布时间】:2013-03-27 17:50:32
【问题描述】:

我想使用 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

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

或

yourstring = "L%sLL" % yourstring

或

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

我显然在这里遗漏了一些东西。我能做什么?

【问题讨论】:

  • 你考虑过使用sed,还是打算使用python? sed 's#$#LL' input_file | sed 's#^#L#' > output_file 可能比 python 做的任何事情都快。

标签: python line add


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多