Reputation: 27069
I want to join N strings together, one line for each item:
my_list=['one', 'two', 'three']
lines='\n'.join(my_list)
Unfortunately I need a trailing newline at the end of each line in lines
. In the above solution the last line is missing the newline.
... I use Python 2.7
Upvotes: 5
Views: 9089
Reputation: 9914
In Python 3.6, you may also use generator expression (PEP289):
''.join(f"{row}\n" for row in my_list)
It's a bit cleaner to me.
Upvotes: 6
Reputation: 2560
Using print before, it works:
>>> print '\n'.join(ls)
one
two
three
>>>
Check this answer for details on the difference on strings and string representation like mentioned here.
Here as well, you can find a solution.
Upvotes: 0
Reputation: 78780
Alternatively to manually adding to the return value of join, you could (manually as well) append the empty string to your list.
>>> my_list=['one', 'two', 'three']
>>> my_list.append('')
>>> '\n'.join(my_list)
'one\ntwo\nthree\n'
Upvotes: 1
Reputation: 8769
Just add another \n
like this(since the output of join()
is also a string):
my_list=['one', 'two', 'three']
print '\n'.join(my_list)+'\n'
Upvotes: 7