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