Issue
I'm using this line in my code for counting uppercase letters in a string:
text = "Áno"
count = sum(1 for c in text if c.isupper())
This code returns 0, but I expect 1 (as 'Á' is uppercase) How can I count uppercase letters with Unicode characters?
Solution
For python 2 you need to add a u
, your string is not actually unicode:
text = u"Áno"
You can also write your expression as count = sum(c.isupper() for c in text)
, c.isupper()
will return True or False so 1 or 0.
In [1]: text = "Áno"
In [2]: count = sum(c.isupper() for c in text)
In [3]: count
Out[3]: 0
In [4]: text = u"Áno"
In [5]: count = sum(c.isupper() for c in text)
In [6]: count
Out[6]: 1
In [7]: text = "Áno".decode("utf-8")
In [8]: count = sum(c.isupper() for c in text)
In [9]: count
Out[9]: 1
Answered By - Padraic Cunningham
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.