0

Let's say, one has stored the stdout of a shell command in a variable. Example for demonstration:

#!/usr/bin/python

import subprocess

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

Variable output now holds content similar to this:

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

How could one append something to each line besides the last line? So it looks like the following?

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'

It would be possible to count the line numbers, to iterate through it, construct a new string and omit appending for the last line... But... Is there a simpler and more efficient way?

3 Answers 3

1

"append[ing] a string at the end of each line" is equivalent to replacing each newline with string + newline. Sooo:

s = "Usage...\nConcatenate...\n...\nFor complete..."
t = s.replace("\n", "<br><br>\n")
print t
Sign up to request clarification or add additional context in comments.

Comments

0

How about this:

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

You can do this all in one line:

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

Comments

0

If you want to also keep the '\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'

Otherwise just do '<br></br>'.join()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.