python - 如何在特定位置将句子插入字符串?
问题描述
假设有这样一行:
<a href="//gifts.ru/catalog/model-futbolka-imperial"> Imperial 190 </a> is a premium model, decoration of any promotion and a worthy personal gift. Soft, comfortable tight T-shirt, with a collar protected from deformation. It holds its shape perfectly and is ideal for applying a logo. The absence of side seams allows you to apply the image almost over the entire surface. <br>
告诉我如何做到这一点?我想做find ('.')
,但它不起作用,因为点也在链接中
<a href="//gifts.ru/catalog/model-futbolka-imperial"> Imperial 190 </a>
预期输出:
<a href="//gifts.ru/catalog/model-futbolka-imperial"> Imperial 190 </a> is a premium model, decoration of any promotion and a worthy personal gift. **[INSERTED TEXT]**. Soft, comfortable tight T-shirt, with a collar protected from deformation. It holds its shape perfectly and is ideal for applying a logo. The absence of side seams allows you to apply the image almost over the entire surface. <br>
会有很多这样的插入。
解决方案
您可以先找到.
出现在 之后的第一个索引,</a>
然后在切片的帮助下附加要插入的文本。但是,这取决于主要文本始终位于锚标记之后的假设......
text = "Text to be inserted."
to_parse = '<a href="//gifts.ru/catalog/model-futbolka-imperial"> Imperial 190 </a> is a premium model, decoration of any promotion and a worthy personal gift. Soft, comfortable tight T-shirt, with a collar protected from deformation. It holds its shape perfectly and is ideal for applying a logo. The absence of side seams allows you to apply the image almost over the entire surface. <br>'
index = to_parse.find(".", to_parse.find("</a>"))
to_parse = to_parse[:index+1] + text + to_parse[index+1:]
print(to_parse)
您可以根据需要通过编辑切片语句来调整插入文本之前或之后的间距和/或句号。