简体   繁体   中英

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?

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.

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 " ".

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM