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
Active
Viewed 1.1e+01k times
5 Answers
69
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)

Sam Dolan
- 31,966
- 10
- 88
- 84
10
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

David
- 17,673
- 10
- 68
- 97
6
Use string.isupper() with filter()
>>> letters = "asdfHRbySFss"
>>> def isCap(x) : return x.isupper()
>>> filter(isCap, myStr)
'HRSF'

willie
- 61
- 1
- 3
3
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()

Coolkid
- 33
- 7
1
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']

jcchuks
- 881
- 8
- 16
-
There's a string of all uppercase ASCII characters built into Python: `from string import ascii_uppercase`. Doing it this way is likely faster than calling `isupper` on every letter, but I haven't timed it. If you're using it over it over, you might even get it to go faster by transforming that string into a set of individual characters. – MTKnife Oct 28 '20 at 21:36