繁体   English   中英

如何在保持 \\n 的同时拆分字符串

[英]How to split string while keeping \n

我想写每个项目的第一个字母,而换行符保持不变,但是当我将列表转换为字符串时,它写在一行中。 像这样"I wtwfloe I wlss"但我希望输出看起来像这样"I wt \\nwtfl \\noei \\nwl \\nss"

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)

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

当您不提供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

通过正则表达式

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

import re

string = re.sub(r"(.)\S+(\s)", r"\1\2", r + " ")[:-1]

print(string)

输出:

I t
w t f l 
o e i
w l
s s

您正在做的是 -从列表中的每个单词中获取第一个字母,然后加入它们。 您没有跟踪字符串中的\\n

你可以这样做。

list_of_words = r.split('\n')
m = [[x[0] for x in y.split()] for y in list_of_words]
for i in m:
    string = ' '.join(i)
    print(string)
Output

I w t
w t f l
o e i
w l
s s

这是使用while循环的解决方案

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


total_lines = len(r.splitlines())
line_no = 0
while line_no < total_lines:
    words_line = r.splitlines()[line_no]
    list_of_words = words_line.split()
    m = [x[0] for x in list_of_words]
    print(' '.join([str(item) for item in m]))
    line_no = line_no + 1

由于已经提供了许多有效的方法,这里有一个很好且全面的方法来完成相同的任务,而不使用str.split() ,这会在内存中创建不必要的列表中间体(但在这种情况下它并不代表任何问题)。

此方法利用str.isspace()在一行中提供整套指令:

string = "".join([string[i] for i in range(len(string)) if string[i].isspace() or string[i-1].isspace() or i == 0])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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