2015-02-04 497 views
0

比方說,我們將shell命令的stdout存儲在一個變量中。實例演示:如何在python中每行字符串的末尾添加一個字符串?

#!/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' 

這將有可能算的行號,來遍歷它,構造新的字符串並省略附加最後一行...但是...有沒有更簡單和更有效的方式?

回答

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 
1

「追加[和]在每行的最後一個字符」相當於用字符串+換行符替換每個換行符。 SOOO:

s = "Usage...\nConcatenate...\n...\nFor complete..." 
t = s.replace("\n", "<br><br>\n") 
print t 
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()

相關問題