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

时间:2016-11-02 13:12:27

标签: 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>并删除空格(我想保留两者)

抱歉这个微不足道的问题,但我找不到解决方案

3 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

您可以使用正则表达式。

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)

答案 2 :(得分:0)

您可以使用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>