问题
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?
回答1:
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)
回答2:
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
回答3:
Use string.isupper() with filter()
>>> letters = "asdfHRbySFss"
>>> def isCap(x) : return x.isupper()
>>> filter(isCap, myStr)
'HRSF'
回答4:
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()
回答5:
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']
来源:https://stackoverflow.com/questions/4697535/how-can-i-check-if-a-letter-in-a-string-is-capitalized-using-python