假设我有大量没有换行符的 HTML。我想将每个元素放入一个列表中。
input = "<head><title>Example Title</title></head>"
a_list = ["<head>", "<title>Example Title</title>", "</head>"]
诸如此类。在每个 >< 之间拆分.
但是在 Python 中,我不知道有什么方法可以做到这一点。我只能拆分 at 该字符串,这会将其从输出中删除。我想保留它,并在两个相等运算符之间拆分。
如何做到这一点?
编辑:最好不要将字符添加回每个列表项的末尾。
请您参考如下方法:
# initial input
a = "<head><title>Example Title</title></head>"
# split list
b = a.split('><')
# remove extra character from first and last elements
# because the split only removes >< pairs.
b[0] = b[0][1:]
b[-1] = b[-1][:-1]
# initialize new list
a_list = []
# fill new list with formatted elements
for i in range(len(b)):
a_list.append('<{}>'.format(b[i]))
这将在 python 2.7.2 中输出给定的列表,但它也应该在 python 3 中工作。
