如问题所述:
您可以检查字符串是否为XML标记,如果它以
<
开头并以>
结尾
您需要迭代列表中的每个字符串,并使用str.startswith()
和str.endswith()
检查第一个和最后一个字符:
In [1]: l = ["<string1>", "somethingelse", "</string1>"]
In [2]: [item for item in l if item.startswith("<") and item.endswith(">")]
Out[2]: ['<string1>', '</string1>']
这里我们只是在list comprehension中过滤了所需的字符串,但为了计算我们有多少匹配,我们可以使用sum()
每次匹配时添加1
:
In [3]: sum(1 for item in l if item.startswith("<") and item.endswith(">"))
Out[3]: 2
这只是一种方法,我不知道你的课程有多远。一个更天真,更直接的答案版本可能是:
def tag_count(l):
count = 0
for item in l:
if item.startswith("<") and item.endswith(">"):
count += 1
return count