How can I check if a letter in a string is capitalized using python?

Question:

I have a string like “asdfHRbySFss” and I want to go through it one character at a time and see which letters are capitalized. How can I do this in Python?

Asked By: clayton33

||

Answers:

Use string.isupper()

letters = "asdfHRbySFss"
uppers = [l for l in letters if l.isupper()]

if you want to bring that back into a string you can do:

print "".join(uppers)
Answered By: Sam Dolan

Use string.isupper() with filter()

>>> letters = "asdfHRbySFss"
>>> def isCap(x) : return x.isupper()
>>> filter(isCap, myStr)
'HRSF'
Answered By: willie

Another, more compact, way to do sdolan’s solution in Python 2.7+

>>> test = "asdfGhjkl"
>>> print "upper" if any(map(str.isupper, test)) else "lower"
upper
>>> test = "asdfghjkl"
>>> print "upper" if any(map(str.isupper, test)) else "lower"
lower
Answered By: David
m = []
def count_capitals(x):
  for i in x:
      if i.isupper():
        m.append(x)
  n = len(m)
  return(n)

This is another way you can do with lists, if you want the caps back, just remove the len()

Answered By: Coolkid

Another way to do it using ascii character set – similar to @sdolan

letters = "asdfHRbySFss"
uppers = [l for l in letters if ord(l) >= 65 and ord(l) <= 90] #['H', 'R', 'S', 'F']
lowers= [l for l in letters if ord(l) >= 97 and ord(l) <= 122] #['a', 's', 'd', 'f', 'b', 'y', 's', 's']
Answered By: jcchuks
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.