8
I have declared two certain variables, one of which is uppercase and the other only lowercase. See the example below:
actor = "Jon Snow"
pet = "wolf"
How can I identify if it exists at least one capital letter in string?
8
I have declared two certain variables, one of which is uppercase and the other only lowercase. See the example below:
actor = "Jon Snow"
pet = "wolf"
How can I identify if it exists at least one capital letter in string?
10
Perhaps comparing the converted string to lower case would be easier.
texto = 'não tem maiúsculas'
if texto.lower() == texto:
print("não tem maiúsculas")
Another way would be using the function any
to check if any character of the string is evaluated as True
when calling the method isupper
.
Behold:
texto = 'meu texto tem caracteres com Maiúsculas'
if any(x.isupper() for x in texto):
print('Tem maiúscula')
the first way is the most efficient, the second the "coolest" :-) in an ideal world would be the "one and obvious way" - but unfortunately we have a big overhead to call functions from Python code paracada character.
@jsbueno it is beautiful to see this expression with any
. I didn’t know what it was for any
in Python, but I imagined what it was for. I even made a question to help those who don’t know.
It has "any" and "all" - for small things, when what is done in the expression is proportionally more complicated than in this case, it is very practical. But for a text of a few dozen KB, for example, the difference between your two methods is significant.
@jsbueno in this case, if the use of any
is heavy, with regex would be even worse, right?
Not - why regex uses an optimized engine running in native code. The any
gets heavy there because it makes a call Function in Python for each character, while the upper
will directly transform all characters into a single function in native code. (will use more memory also - o isupper
would use a few dozen bytes for each call, at most, reused - o upper
will always create another entire string - if it’s dozens of MB of text makes a difference.
Now regexp has to use \w
, of course - only that it takes all the letters,s ma snao distinguishes uppercase and lowercase: it is not trivial to solve this with regexp.
@jsbueno thanks, man. The first thing that comes to mind when talking about regex
is the "weight". I did not know this difference :p
2
Using regex becomes 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 upper case 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']
Works well for those who do not use accents, but with accents? I do not believe that for a simple thing Regex will be faster or simpler than .lower()
.
I edited and placed the solution with accents. I did not say that the solution with regex is faster, for that we would have to do tests, but in my opinion it is simpler and more pythonico, It is not by chance that Django elected regex for the routing of Urls, incidentally the documentation highlights that for simple cases, regex is one of the best solutions, some authors say it is unbeatable.
You said rápido
and eficiente
, both lead to understand exactly this, which is not a fact, but micro-optimization is minimal even, however it would change the text, because it is not true, maybe it means something else, but people will misunderstand the way it was written, about regex in Django’s Urls, this is to facilitate development and not because X is better Y, it is better in condition in need of creating custom Urls, does not mean that you will need a cannon whenever you want to kill ants.
Maybe it’s a practical way to retrieve the uppercase letters, but it’s certainly not the most pythonic of just checking if they exist, as is asked in the problem. Only the if
using the lower
already solves the issue and becomes much more readable the code.
I said Fast, Simple and Efficient, but I didn’t say at any time that it’s better, or that x is better than y. Also, I tried to make it clear that this is my opinion. My intention was only to present one more alternative, which can meet only the question itself which is to detect the presence of maiuscula (search-enabled) plus (findall) to detect all . Under stress. :-)
As I said before, what you write can be interpreted in different ways, is a tip, guidance, so understand as such for you to improve and not as a criticism.
2
A possible solution would be to iterate through the characters in the string and ask what their Category General Unicode via the standard library function unicodedata.category()
.
In this case the search is for the category Lu
which means Letter Uppercase or capital letters
import unicodedata
s = "pÁssaro"
for c in s:
if unicodedata.category(c) == "Lu":
print('Existem letras maiúsculas.')
break
else:
print('Não há letras maiúsculas.')
Test the code on Repl.it
It is worth mentioning that isupper()
would be equivalent to: according to documentation, internally it (and other methods such as islower
) checks the Unicode category.
1
Can do:
p = "Jon Snow"
for x in p:
c = ord(x)
if c >= 65 and c <= 90:
print("Maiscula encontrada")
"Assuming ASCII" is already wrong. Please read http://local.joelonsoftware.com/wiki/O_M%C3%Adnimo_absoluto_que_todos_programadores_de_software_precise,_Absolutely,Positivamente_de_Saber_Sobre_Unicode_e_Conjuntos_de_Caracteres(Apologies!)
Why not use the string package if it is only to take the uppercase of such a set..
0
Another interesting way to resolve this issue is by implementing a function of the type def
. In this case the code would be:
def maiuscula(p):
if any(i.isupper() for i in p):
return True
return False
palavra = input('Digite uma palavra: ')
print(maiuscula(palavra))
This function takes a word and checks if there are uppercase letters in it and, if there is , at least 1 uppercase letter the function returns True. Otherwise, it returns False.
Browser other questions tagged python
You are not signed in. Login or sign up in order to post.
I don’t know what your entrees will be, but you can try something with
.istitle
. Return true if all string initials are uppercase, eg:. " The Awakening of Force" and false for "The awakening of force" or "the awakening of force".– vinibrsl
@Vinicius but would need to identify in any position. For example, if it was a password, check if it has at least one uppercase letter.
– viana