2

For example, I have the code here:

string_list = ['a', 'b', 'c\n', 'd', 'e', 'f']
print(' '.join(string_list))

The output will be:

a b c
 d e f

How to get the result of:

a b c
d e f

instead?

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Han
  • 35
  • 4
  • Does this answer your question? [How can I remove a trailing newline?](https://stackoverflow.com/questions/275018/how-can-i-remove-a-trailing-newline) – AMC Feb 20 '20 at 19:54
  • 2
    What's the context for this? It seems rather awkward, no? – AMC Feb 20 '20 at 19:59
  • Sorry for lacking the background... I am just learning Python and playing with Jupyter Notebook... – Han Feb 20 '20 at 20:04
  • That's fine, don't worry, I was just curious. It's a toy example? – AMC Feb 20 '20 at 20:06
  • Yes, I am trying the join() function, and trying to add '\n' just for fun – Han Feb 20 '20 at 20:14

3 Answers3

2

This seems to work:

string_list = ['a', 'b', 'c\n', 'd', 'e', 'f']

output = "".join(x + " " if not "\n" in x else x for x in string_list)[:-1]

print(output)

Output:

a b c
d e f

As @wjandrea pointed out, we can use s if s.endswith('\n') else s + ' ' for s in string_list instead of x + " " if not "\n" in x else x for x in string_list. We could also use x if x[-1] == "\n" else x + " " for x in string_list. Both are a bit cleaner.

Ed Ward
  • 2,333
  • 2
  • 10
  • 16
0

It's pretty simple if you ignore join entirely.

string_list = ['a', 'b', 'c\n', 'd', 'e', 'f']
output = ""
for string in string_list:
    output += string + (" " if not string.endswith("\n") else "")
output = output.rstrip() # If you don't want a trailing " ".
Guimoute
  • 4,407
  • 3
  • 12
  • 28
0

Thanks everyone for answering my question. I came up with a solution myself:

string_list = ['a', 'b', 'c\n', 'd', 'e', 'f']
joined_string = ' '.join(string_list)
print(joined_string.replace('\n ', '\n'))

It works!

Han
  • 35
  • 4