How to split string while keeping \n

Viewed 104

I want to write the first letter of every item while linebreak stays the same but when I turn the list to string it's written in one line. Like this "I w t w f l o e I w l s s" but I want output to look like this "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)
5 Answers

What you are doing is you are splitting all the lines in a single go, so you are losing the information of each line. You need to create list of list to preserve the line information.

When you provide no argument means split according to any whitespace, that means both ' ' 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

Via regexp

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)

Output:

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

What you're doing is - Get the first letter from each word of the list and then joining them. You are not keeping track of the \n in the string.

You could do this instead.

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

Here is the solution by using while loop

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

Since many valid methods were already provided, here's a nice and comprehensive way of doing the same task without the use of str.split(), which creates unnecessary list intermediates in memory (not that it represents any problem in this case though).

This method takes advantage of str.isspace() to deliver the whole set of instructions in one line:

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