Reputation: 35
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?
Upvotes: 2
Views: 908
Reputation: 2331
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.
Upvotes: 2
Reputation: 35
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!
Upvotes: 0
Reputation: 4649
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 " ".
Upvotes: 0