I am trying to write code to count the number of upper case letters in a string using Python. I have written the following but instead of the code returning the number of Upper Case letters it returns []? An help would be gratefully recieved.

import re

while True:
    strPassword = input("Please enter your password: ")
    length = len(strPassword)
    if length < 6 or length > 12:
        print ("It is not the correct length")
print ("Password OK")

upper = 0
lower = 0
number = 0

print (re.findall("A-Z", strPassword, 0))

Recommended Answers

All 3 Replies

Member Avatar

[] is an empty list. re.findall returns a list.
What you've done is miss a bit of re syntax.
Here's a tip -

>>> re.findall('A-Z','A-Z')
>>> re.findall('A-Z','A-ZsjdjoA')
>>> re.findall('[A-Z]','A-Z')
['A', 'Z']
>>> re.findall('[A-Z]','A-ZsjdjoA')
['A', 'Z', 'A']

See the difference? ;)

Enalicho has give some tip.
Here a couple more.
Always use r(raw_string) for regex expression.
If you want to count,just use len() because re.findall() is returning a list.
Here is a example run.

>>> import re
>>> user_input = 'aaaaBBBCC'
>>> re.findall(r'A-Z', user_input)
>>> #Missing []
>>> re.findall(r'[A-Z]', user_input)
['B', 'B', 'B', 'C', 'C']
>>> #Count
>>> len(re.findall(r'[A-Z]', user_input))
commented: Good call; I shouldn't have left out the r +1

Ah ha! Thanks thats great.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.