简体   繁体   中英

How do I insert a sentence into a string at a specific location?

Let's say there is a line like this:

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

Tell me how this can be done? I wanted to do find ('.') , But it won't work, since the dot is also in the link

<a href="//gifts.ru/catalog/model-futbolka-imperial"> Imperial 190 </a>

Expected output:

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

There will be a lot of such insertions.

You can first find the index of the first . which occurs after the </a> and append the text which you want to insert with the help of slicing. However, this depends on the assumption that the main text is always coming after an anchor tag....

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)

You can adjust the spacing and/or fullstops which come before or after the inserted text as per your requirement by editing the slicing statement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM