Search code examples
pythonpython-3.xuppercaselowercasepython-re

Why isupper() function doesnt work in if condition?


My code looks like :


import re

lst=[]

b = [('to', 1), ('Me', 2), ('And', 3), ('one', 5), ('listen', 6), ('up', 7)]

#print(type(b[2][0]))
count = 0 
for i in range(len(b)):
    
    if b[i][0].isupper():
        count = count + 1

        r = re.findall('([A-Z][a-z]+)', b[i][0])
        print(r)

print(count)

i want to see capitalized words as result , like :

["Me"]
["And"]

But i get nothing and the count shows 0 number of capitalized words!

The weird thing is if i use islower() it works and it shows all words that are not capitalized!!


import re

lst=[]

b = [('to', 1), ('Me', 2), ('And', 3), ('one', 5), ('listen', 6), ('up', 7)]

#print(type(b[2][0]))
count = 0 
for i in range(len(b)):
    
    if b[i][0].islower():
        count = count + 1

        r = re.findall('([a-z]+)', b[i][0])
        print(r)

print(count)  



How can i fix this?


Solution

  • Use istitle instead of isupper.

    import re
    
    lst=[]
    
    b = [('to', 1), ('Me', 2), ('And', 3), ('one', 5), ('listen', 6), ('up', 7)]
    
    #print(type(b[2][0]))
    count = 0 
    for i in range(len(b)):
        
        if b[i][0].istitle():
            count = count + 1
    
            r = re.findall('([a-z]+)', b[i][0])
            print(r)
    
    print(count)