CandyGum CandyGum - 2 years ago 79
Python Question

Add tex to end of all lines in string - Python

Say I have this string:


How do I add something at the end of all the lines? The amount of lines in the string may vary from time to time.

Something like:

l = duplicate.split('\n')
l[1]+= 'X'
l = '\n'.join(l)

Duplicate being the string's name.

This code only adds 'x' to the end of line 1.

How can I do this for every line?


Answer Source

First, split as you did duplicate on '\n':

splitted = duplicate.split('\n')

Then append 'x' at the end of each line with a for, and join these line on '\n'. I do both operations in a signle line:

"\n".join(line + "x" for line in splitted)

If you're not familiar with generator expressions, this is somewhat similar to:

withSuffixes = []
for line in l:
    withSuffixes.append(splitted + "x")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download