1

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.

1
  • 2
    Check if i is \n before printing and use end = "" if so. Commented Sep 25, 2020 at 1:36

4 Answers 4

3
x = ['a', 'b', 'c', '\n', 'a1', 'b1', 'c1'] for i in x : print(i , end = " " if i != '\n' else '') 
Sign up to request clarification or add additional context in comments.

Comments

1

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 

2 Comments

First solution to join /replace works just fine... Could you please look at the solution i found on my own ?
If your solution works for you then use it. It doesn't quite give the same output as you eliminated the space between elements on the second row. I would probably combine a join with format if you are looking for a more tabular output, there are plenty of examples on SO showing how.
0

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 

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.