例如,我这里有代码:
string_list = ['a', 'b', 'c\n', 'd', 'e', 'f']
print(' '.join(string_list))
输出将是:
a b c
d e f
如何获得结果:
a b c
d e f
相反?
最佳答案
这似乎有效:
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)
输出:
a b c
d e f
正如 @wjandrea 指出的,我们可以使用 s if s.endswith('\n') else s + ' ' for s in string_list
而不是 x + ""if not “\n” in x else x for x in string_list
。我们还可以使用x if x[-1] == "\n"else x + ""for x in string_list
。两者都更干净一些。
关于python - 在Python中使用字符串连接函数时如何跳过 "\n"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60327536/