Identify if there is a capital letter in the string

6

I have declared two certain variables, one of which has a capital letter and the other only lowercase. See the example below:

actor = "Jon Snow"
pet = "wolf"

How can I identify if there is at least one uppercase letter in string ?

    
asked by anonymous 29.03.2017 / 16:36

3 answers

7

Maybe comparing the string converted to lowercase would be easier.

texto = 'não tem maiúsculas'

if texto.lower() == texto:
   print("não tem maiúsculas")

Another way would be to use the any function to check if any character in the string evaluates to True when calling the isupper method.

See:

texto = 'meu texto tem caracteres com Maiúsculas'

if any(x.isupper() for x in texto):
     print('Tem maiúscula')
    
29.03.2017 / 16:44
1

You can do:

p = "Jon Snow"
for x in p:
  c = ord(x)
  if c >= 65 and c <= 90:
    print("Maiscula encontrada")
    
29.03.2017 / 17:01
1
  

Using regex gets fast, simple and efficient:

>>>import re

>>> # Retornando a primeira Maiúscula
... print (re.search('[A-Z]', 'Jon Snow').group())
J

>>> # Retornando todas as maiúsculas
... print (re.findall('[A-Z]','Jon Snow'))
['J', 'S']

If there is no capitulo in the first case, the return would be None, in the second an empty list.

  

Solution for accentuation

>>> import unicodedata as uncd
>>> print (re.findall('[A-Z]',uncd.normalize('NFKD','Jon Snow É o Á')) )
['J', 'S', 'E', 'A']
    
31.03.2017 / 01:30