[英]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.我有一个像“asdfHRbySFss”这样的字符串,我想一次遍历一个字符,看看哪些字母是大写的。 How can I do this in Python?
我怎样才能在 Python 中做到这一点?
Use string.isupper()使用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+在 Python 2.7+ 中执行 sdolan 解决方案的另一种更紧凑的方法
>>> 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()使用 string.isupper() 和 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()这是您可以使用列表的另一种方法,如果您想要大写字母,只需删除 len()
Another way to do it using ascii character set - similar to @sdolan另一种使用 ascii 字符集的方法 - 类似于 @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']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.