开发者

How to Insert tags in texts

I have a text like that

Or like that

I want to insert tags into them:

<tag1>I have a text like that</tag1>
<tag1>Or like that</tag1开发者_C百科>

how can I achieve this in python ?


Sounds more like you want to insert text between tags. Right?

'<tag1>{0}</tag1>'.format('I have a text like that')

If it's a list of strings:

>>> l = ['I have a text like that', 'Or like that']
>>> ['<tag1>{0}</tag1>'.format(s) for s in l]
['<tag1>I have a text like that</tag1>', '<tag1>Or like that</tag1>']


Just treat the tags as normal strings and do the string concatenation operation. That is the basic approach.

You can use str.format operation on string to insert text between tags in the string too.

But if your intention is to create a well formed XML Document, then Python provides a library called ElementTree

from xml.etree import ElementTree as ET

root = ET.Element("root")
tag1 = ET.SubElement(root,"tag1")
tag1.text = "hi"
tag1 = ET.SubElement(root,"tag1")
tag1.text = "hello"
tree = ET.ElementTree(root)
tree.write('s.html')


I am sorry, I have never done python, but what you may do is split each line using regex for a newline and store the lines in an array. Append the tags on each line and then combine them together using foreach loop...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜