John Veridan
John Veridan

Reputation: 101

Line Breaks by Single Quotation in Python

I have this right now in Python:

"Going to school.
Taking a few courses and playing basketball.
Got a new puppy."
"Going to school.
I bought a new backpack yesterday.
Got a new cat.
I did my homework as well."
"Going to school.
Brought lunch today."

I am trying to figure out how I place line breaks in here from whenever " occurs so I have sentences that are in quotations on each line.

I think regex might be the way, but not certain. Any advice?

Upvotes: 0

Views: 1014

Answers (1)

Jean-François Fabre
Jean-François Fabre

Reputation: 140276

Just extract the data within the quotes using re.DOTALL flag to consider endline like any other character, and use "non-greedy" mode

t = """"Going to school.
Taking a few courses and playing basketball.
Got a new puppy."
"Going to school.
I bought a new backpack yesterday.
Got a new cat.
I did my homework as well."
"Going to school.
Brought lunch today." """

import re

print(re.findall('".*?"',t,flags=re.DOTALL))

prints the list of extracted sentences, within quotes.

['"Going to school.\nTaking a few courses and playing basketball.\nGot a new puppy."',
'"Going to school.\nI bought a new backpack yesterday.\nGot a new cat.\nI did my homework as well."',
'"Going to school.\nBrought lunch today."']

Now that we extracted the data properly, joining that list of strings with linebreaks and replacing the inner linebreaks by spaces is easy now:

print("\n".join([x.replace("\n"," ") for x in re.findall('".*?"',t,flags=re.DOTALL)]))

output:

"Going to school. Taking a few courses and playing basketball. Got a new puppy."
"Going to school. I bought a new backpack yesterday. Got a new cat. I did my homework as well."
"Going to school. Brought lunch today."

Upvotes: 1

Related Questions