guettli
guettli

Reputation: 27069

Create lines of text, '\n'.join(my_list) is missing trailing newline

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

Answers (4)

Chuan Ma
Chuan Ma

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

rocksteady
rocksteady

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

timgeb
timgeb

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

riteshtch
riteshtch

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

Related Questions