首页 > 解决方案 > 如何在保留 \n 的同时拆分字符串

问题描述

我想写每个项目的第一个字母,而换行符保持不变,但是当我将列表转换为字符串时,它写在一行中。像这样"I w t w f l o e I w l s s",但我希望输出看起来像这样"I w t \n w t f l \n o e i \n w l \n s s"

r = '''I want to
write the first letter 
of every item
while linebreak
stay same'''

list_of_words = r.split()
m = [x[0] for x in list_of_words]
string = ' '.join([str(item) for item in m])
print(string)

标签: pythonlist

解决方案


您正在做的是一次拆分所有行,因此您丢失了每行的信息。您需要创建列表列表以保留行信息。

当您提供no argument means split according to any whitespace时,这意味着两者' ' and '\n'

r = '''I want to
write the first letter 
of every item
while linebreak
stay same'''

list_of_words = [i.split() for i in r.split('\n')]
m = [[y[0] for y in x] for x in list_of_words]
string = '\n'.join([' '.join(x) for x in m])
print(string)
I w t
w t f l
o e i
w l
s s

推荐阅读