简体   繁体   中英

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

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?

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)

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

Use string.isupper() with filter()

>>> letters = "asdfHRbySFss"
>>> def isCap(x) : return x.isupper()
>>> filter(isCap, myStr)
'HRSF'
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()

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']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM