Pericles Faliagas
Pericles Faliagas

Reputation: 636

Join split lines of a string variable when there is no gap between them

I have a multi-line string variable (var_text), which look like the following:

'I am a
high
school
student

I like
Physics'

What i am trying to do is join the split lines that have no gap between them so that the variable looks like the following:

'I am a high school student

I like Physics'

I have tried to use the following line of code

" ".join(var_text.splitlines())

but it joins all the lines regardless of the gaps between them, so the end result looks like this:

'I am a high school student    I like Physics'

Any suggestions?

Upvotes: 1

Views: 1776

Answers (3)

The Pilot Dude
The Pilot Dude

Reputation: 2237

Try this:

text = '''I am a
high
school
student

I like
Physics'''

joined = " ".join(text.splitlines())
joined_split = joined.replace("  ", "\n")
print(joined_split)

This basically replaces the double space between both lines in your code with a new line. If you wanted to store the 2 variables in a list, you could use this:

text = '''I am a
high
school
student

I like
Physics'''

joined = " ".join(text.splitlines())
joined_split = joined.split("  ")
print(joined_split)

This returns a list with each line as a list. A list might be useful later (I have no idea :)

Upvotes: 1

Pierre D
Pierre D

Reputation: 26211

Try:

out = '\n\n'.join([rec.replace('\n', ' ') for rec in s.split('\n\n')])

Out:

'I am a high school student

I like Physics'

Upvotes: 1

Thibault D.
Thibault D.

Reputation: 301

You can achieve that with a simple for loop, where you create a new line in your new string when you find an empty line in the original string:

s = """'I am a
high
school
student

I like
Physics'"""

r = ""
for line in s.splitlines():
    if line == "":
        r += "\n"
    else:
        r += " " + line
r = r[1:] # Remove the first space

Upvotes: 1

Related Questions