TransWikia.com

How to use "n" to change line but still print rest of the elements in single line

Stack Overflow Asked by DS_ on January 17, 2021

Using code below –

x = ['a', 'b', 'c', 'n', 'a1', 'b1', 'c1']
for i in x :
    print(i , end = " ")

I want to get the output –

a b c
a1 b1 c1

Currently it shifts a1 by one space –

a b c
 a1 b1 c1

If i don’t use end =" " all elements are printed in their own line.

4 Answers

Generally, I would look to use str.join() instead of looping through individual elements, e.g.:

for i in x:
    print(i, end=' ')

Is nearly equivalent to (ignoring the spurious space at the end for the above):

print(' '.join(x))

But you have a small wrinkle in that it also surrounds the 'n' with spaces so you want to replace ' n ' with 'n', so:

In []:
print(' '.join(x).replace(' n ', 'n'))

Out[]:
a b c
a1 b1 c1

Or you can get a little over engineered and consider this a problem of splitting the list on a value (in this case 'n') and then printing out the groups:

In []:
import itertools as it
print('n'.join(' '.join(g) for k, g in it.groupby(x, lambda a: a == 'n') if !k))

Out[]:
a b c
a1 b1 c1

Correct answer by AChampion on January 17, 2021

Created also next fancy solution just for fun:

x = ['a', 'b', 'c', 'n', 'a1', 'b1', 'c1']
print(*map(lambda s: s + (' ', '')[s.endswith('n')], x), sep = '')

It takes into account the fact that in order to print a list of strings x you just need to do:

print(*x)

which is same and the shortest way to do what was done by the initial questioner's next code:

for i in x :
    print(i , end = " ")

This * operation is called unpacking.

Answered by Arty on January 17, 2021

I kind of found another solution myself... so this works too .. kind of - can you guys suggest on this.

x = ['a', 'b', 'c', 'n', 'a1', 'b1', 'c1']

y = ""
for i in x:
    y = y + i.rjust(2,)
    
print(y)

output -

 a b c 
a1b1c1

Answered by DS_ on January 17, 2021

x = ['a', 'b', 'c', 'n', 'a1', 'b1', 'c1']
for i in x :
    print(i , end = " " if i != 'n' else '')

Answered by Arty on January 17, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP