如何在python的字符串的每一行的末尾追加一个字符串?

时间:2015-02-04 20:42:08

标签: python string append

假设有人将shell命令的stdout存储在变量中。演示示例:

#!/usr/bin/python

import subprocess

proc = subprocess.Popen(['cat', '--help'], stdout=subprocess.PIPE)
output = proc.stdout.read()

变量output现在包含与此类似的内容:

Usage: cat [OPTION]... [FILE]...
Concatenate FILE(s), or standard input, to standard output.
...
For complete documentation, run: info coreutils 'cat invocation'

除了最后一行之外,怎么能在每一行附加一些东西?所以它看起来如下?

Usage: cat [OPTION]... [FILE]...<br></br>
Concatenate FILE(s), or standard input, to standard output.<br></br>
...<br></br>
For complete documentation, run: info coreutils 'cat invocation'

可以计算行号,迭代它,构造一个新字符串并省略追加到最后一行......但是......有更简单,更有效的方法吗?

3 个答案:

答案 0 :(得分:1)

“在每行的末尾附加一个字符串”相当于用字符串+换行符替换每个换行符。 SOOO:

s = "Usage...\nConcatenate...\n...\nFor complete..."
t = s.replace("\n", "<br><br>\n")
print t

答案 1 :(得分:0)

这个怎么样:

line_ending = '\n'
to_append = '<br></br>'

# Strip the trailing new line first
contents = contents.rstrip([line_ending])

# Now do a replacement on newlines, replacing them with the sequence '<br></br>\n'
contents = contents.replace(line_ending, to_append + line_ending)

# Finally, add a trailing newline back onto the string
contents += line_ending

您可以在一行中完成所有操作:

contents = contents.rstrip([line_ending]).replace(line_ending, to_append + line_ending) + line_ending

答案 2 :(得分:0)

如果您还要保留'\n'

>>> '<br></br>\n'.join(output.split('\n'))

Usage: cat [OPTION]... [FILE]...<br></br>
Concatenate FILE(s), or standard input, to standard output.<br></br>
...<br></br>
For complete documentation, run: info coreutils 'cat invocation'

否则只需'<br></br>'.join()