Check if any character of a string is uppercase Python

放肆的年华 提交于 2020-05-23 07:59:10

问题


Say I have a string word.

This string can change what characters it contains.

e.g. 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.


回答1:


You should use str.isupper() and str.isalpha() function.

Eg.

is_all_uppercase = word.isupper() and word.isalpha()

According to the docs:

S.isupper() -> bool

Return True if all cased characters in S are uppercase and there is at least one cased character in S, False otherwise.




回答2:


You could use regular expressions:

all_uppercase = bool(re.match(r'[A-Z]+$', word))



回答3:


Yash Mehrotra has 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:

import string

def is_all_uppercase(a_str):
    for c in a_str:
        if c not in string.ascii_uppercase:
            return False
    return True



回答4:


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




回答5:


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



回答6:


If you like lower level C like implementation for performance improvements, you can use below solution.

def is_upper(word):
      for c in word:
          numValue = ord(c)
          if  numValue != 32 and numValue <= 64 or numValue >= 91 :
               return False
      return True 


来源:https://stackoverflow.com/questions/33883512/check-if-any-character-of-a-string-is-uppercase-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!