'XML Tag Counter

Please see attachment. I am new to python (and programming in general; making a career switch; tldr: I am a noob at this).

I have no idea what function I can write that will return me the number of xml tags in the list. Please help. attached image



Solution 1:[1]

As stated in the question:

you can check if a string is an XML tag if it starts with < and ends with >

You need to iterate over every string in a list and use str.startswith() and str.endswith() to check the first and last characters:

In [1]: l = ["<string1>", "somethingelse", "</string1>"]

In [2]: [item for item in l if item.startswith("<") and item.endswith(">")]
Out[2]: ['<string1>', '</string1>']

Here we just filtered the desired strings in a list comprehension, but to count how many matches we've got, we may use sum() adding a 1 every time there is a match:

In [3]: sum(1 for item in l if item.startswith("<") and item.endswith(">"))
Out[3]: 2

This was though just one way to do it and I am not sure how far have you got in your course. A more naive and straightforward version of the answer might be:

def tag_count(l):
    count = 0
    for item in l:
        if item.startswith("<") and item.endswith(">"):
            count += 1
    return count

Solution 2:[2]

tokens = ['<greeting>', 'Hello World!', '</greeting>']
count = 0

# write your for loop here
for token in tokens:
    if token.startswith("<") and token.endswith(">"):
            count += 1

print(count)

Solution 3:[3]

tokens = ['<greeting>', 'Hello World!', '</greeting>']

count = 0
for token in tokens:
    if token[0] == '<' and token[-1] == '>':
        count += 1

print(count)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 alecxe
Solution 2 Jason Aller
Solution 3 lemon