python - 在Python中使用字符串连接函数时如何跳过 "\n"?

标签 python string

例如,我这里有代码:

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/

相关文章:

string - OleVariant 可用于 DLL 过程中的输出参数吗?

python - 聚合和 Pandas

python - Flask:如何检测用户离开页面?

python - Python 中的总订单

c - C 中的字符串数组

java - String .length() 函数未定义

python - 在终端中将多个函数部署到 Google Cloud Functions?

Python:确定序列中的任何项目是否等于任何其他项目

c++ - ctypes 中的 "char *pList"

python - 删除重音符号并保留在 Python 中的点下