Han
Han

Reputation: 35

How to skip "\n" when using string join function in Python?

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

Answers (3)

Ed Ward
Ed Ward

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

Han
Han

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

Guimoute
Guimoute

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

Related Questions