can somone explain me how this code checks if a word is uppercase

59 Views Asked by At

Here is the code and im struggling to understand the line 5 and 6. I know how isupper() works but i cant understand the combinations going on.

def IndexWords(InputText):
    words = 0
    count = 2
    for i in range(len(InputText)):
        for word in InputText[i].split()[1:]:
            CapitalizationCheck = list(word.strip(','))[0].isupper()
            if CapitalizationCheck == True:
                print('%s:%s' % (count,word))
                words +=1
            count += 1
        count += 1

    if words == 0:
        print('None')

IndexWords(input().split('.'))

This code works just fine but there is too much going on in it(mybe too much for me)

1

There are 1 best solutions below

2
Geom On

There is too much going on! Everything from using capitalisation in variables names to splitting and slicing that can cause things to break easily.

A much more elegant solution would be something like this:

def count_capitalized_words(text):
    words = text.split()
    count = sum(1 for word in words if word.istitle())
    return count

text = "This is an Example Text. It Contains Capitalized Words."
print(count_capitalized_words(text))

Output:

7