CandyGum CandyGum - 1 year ago 218
Python Question

Add text to end of all lines in string

Say I have this string:

"""
iris
jonah
car
donut
"""


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

Desired output:

"""
irisX
jonahX
carX
donutX
"""


Thanks!

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")
"\n".join(withSuffixes)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download