在出现单词时在字符串中创建新行(平凡)

2024-06-28 23:57:14 发布

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

你好,我有这样一句话:

<s>the cat</s><s>sat on a mat</s><s>he wore a hat</s>

我想:

<s>the cat</s>
<s>sat on a mat</s>
<s>he wore a hat</s>

我试过:

thisString.split("</s>")

这是可行的,但是它删除了</s>并删除了空格(我想保留这两个)

对不起,这个问题很琐碎,但我找不到解决办法


Tags: theonhatsatcatsplithe空格
3条回答

你可以使用正则表达式

import re
thisString = "<s>the cat</s><s>sat on a mat</s><s>he wore a hat</s>"
thisString = re.sub("</s>", "</s>\n", thisString)

您可以使用python的join语法。希望这段代码能帮助你

a = '<s>the cat</s><s>sat on a mat</s><s>he wore a hat</s>'
a = '</s>\n'.join(a.split('</s>'))
print a

输出

<s>the cat</s>
<s>sat on a mat</s>
<s>he wore a hat</s>

.split("</s>")

将替换</s>并将每个事件拆分为一个列表

我相信你会想要.replace()

line = '<s>the cat</s><s>sat on a mat</s><s>he wore a hat</s>'
line = line.replace('</s>', '</s>\n')
print (line)

这将用相同的标记替换每个</s>,但在末尾换行

输出为:

<s>the cat</s>
<s>sat on a mat</s>
<s>he wore a hat</s>

相关问题 更多 >