如何使用python检查字符串中的字母是否大写?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4697535/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how can i check if a letter in a string is capitalized using python?
提问by clayton33
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?
我有一个像“asdfHRbySFss”这样的字符串,我想一次遍历一个字符,看看哪些字母是大写的。我怎样才能在 Python 中做到这一点?
采纳答案by Sam Dolan
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)
回答by willie
Use string.isupper() with filter()
使用 string.isupper() 和 filter()
>>> letters = "asdfHRbySFss"
>>> def isCap(x) : return x.isupper()
>>> filter(isCap, myStr)
'HRSF'
回答by David
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
回答by Coolkid
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()
回答by jcchuks
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']

