Python中单引号换行

2024-04-24 09:59:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我现在在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."

我试图弄清楚我是如何从"发生时开始在这里放换行符的,所以每一行都有引用语中的句子。你知道吗

我认为正则表达式可能是一种方式,但不确定。有什么建议吗?你知道吗


Tags: andtonewgotgoingschoolpuppybackpack
1条回答
网友
1楼 · 发布于 2024-04-24 09:59:58

只需使用re.DOTALL标志提取引号中的数据就可以像其他字符一样考虑结束行,并使用“非贪婪”模式

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))

在引号内打印摘录的句子列表。你知道吗

['"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."']

既然我们正确地提取了数据,那么用换行符连接字符串列表并用空格替换内部换行符就很容易了:

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

输出:

"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."

相关问题 更多 >