adrelanos
adrelanos

Reputation: 1593

How to append a string at the end of each line of a string in python?

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?

Upvotes: 0

Views: 1829

Answers (3)

MrAlexBailey
MrAlexBailey

Reputation: 5289

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()

Upvotes: 0

Carsten
Carsten

Reputation: 18446

"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

Upvotes: 1

wrigby
wrigby

Reputation: 126

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

Upvotes: 0

Related Questions