检查字符串的任何字符是否为大写 Python
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33883512/
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
Check if any character of a string is uppercase Python
提问by ffgghhffgghh
Say I have a string word.
假设我有一个字符串词。
This string can change what characters it contains.
这个字符串可以改变它包含的字符。
e.g. word = "UPPER£CASe"
例如 word = "UPPER£CASe"
How would I test the string to see if any character in the string is not uppercase. This string must only contain uppercase letters and no other punctuation, numbers, lowercase letters etc.
我将如何测试字符串以查看字符串中是否有任何字符不是大写。该字符串只能包含大写字母,不能包含其他标点符号、数字、小写字母等。
采纳答案by Yash Mehrotra
You should use str.isupper()
and str.isalpha()
function.
你应该使用str.isupper()
和str.isalpha()
运行。
Eg.
例如。
is_all_uppercase = word.isupper() and word.isalpha()
According to the docs:
根据文档:
S.isupper() -> bool
Return
True
if all cased characters inS
are uppercase and there is at least one cased character inS
,False
otherwise.
S.isupper() -> bool
True
如果 中的所有S
大小写字符都是大写并且 中至少有一个大小写字符,则返回S
,False
否则返回。
回答by Luke Yeager
You could use regular expressions:
您可以使用正则表达式:
all_uppercase = bool(re.match(r'[A-Z]+$', word))
回答by Diogo Martins
Yash Mehrotrahas the best answer for that problem, but if you'd also like to know how to check that without the methods, for purely educational reasons:
Yash Mehrotra为该问题提供了最佳答案,但如果您还想知道如何在没有方法的情况下检查该问题,纯粹出于教育原因:
import string
def is_all_uppercase(a_str):
for c in a_str:
if c not in string.ascii_uppercase:
return False
return True
回答by SvGA
You can alternatively work at the level of characters.
您也可以在字符级别工作。
The following function may be useful not only for words but also for phrases:
以下函数不仅对单词有用,而且对短语也有用:
def up(string):
upper=[ch for ch in string if ch.isupper() or ch.isspace()]
if len(upper)==len(string):
print('all upper')
else:
print("some character(s) not upper")
strings=['UPPERCAS!', 'UPPERCASe', 'UPPERCASE', 'MORE UPPERCASES']
for s in strings:
up(s)
Out: some character(s) not upper
Out: some character(s) not upper
Out: all upper
Out: all upper
回答by STATECHRD
Here you can find a very useful way to check if there's at least one upper or lower letter in a string
在这里您可以找到一种非常有用的方法来检查字符串中是否至少有一个大写或小写字母
Here's a brief example of what I found in this link:
这是我在此链接中找到的内容的简短示例:
print(any(l.isupper() for l in palabra))
https://www.w3resource.com/python-exercises/python-basic-exercise-128.php
https://www.w3resource.com/python-exercises/python-basic-exercise-128.php
回答by Zubair Hassan
If you like lower level C like implementation for performance improvements, you can use below solution.
如果您喜欢较低级别的 C 类实现以提高性能,则可以使用以下解决方案。
def is_upper(word):
for c in word:
numValue = ord(c)
if numValue != 32 and numValue <= 64 or numValue >= 91 :
return False
return True