PDA

View Full Version : uppercase letter in string?



7raTEYdCql
March 21st, 2009, 11:00 PM
How do i check if a string has a uppercase letter in Python??

I searched on the internet but only found stuff that converts Uppercase letters to lower etc??

geirha
March 21st, 2009, 11:03 PM
>>> help(str.isupper)

7raTEYdCql
March 21st, 2009, 11:05 PM
I have to return the index of the uppercase alphabet.

7raTEYdCql
March 21st, 2009, 11:06 PM
isupper checks if all the charachters are upper.

I want to return the index of the character that is upper, not necessary all the characters are upper.

simeon87
March 21st, 2009, 11:09 PM
isupper checks if all the charachters are upper.

I want to return the index of the character that is upper, not necessary all the characters are upper.



>>> str.isupper("aaA"[2])
True

geirha
March 21st, 2009, 11:11 PM
Then you iterate the string and check character for character.


>>> s= "helLo"
>>> for i,c in enumerate(s):
... if c.isupper():
... print i
... break
...
3
>>>

7raTEYdCql
March 21st, 2009, 11:49 PM
How useful is the function enumerate. I mean it can be used in which kind of situations?

simeon87
March 21st, 2009, 11:56 PM
How useful is the function enumerate. I mean it can be used in which kind of situations?

Use the documentation? http://docs.python.org/library/functions.html

Can+~
March 22nd, 2009, 01:00 AM
How useful is the function enumerate. I mean it can be used in which kind of situations?

The usual python for loop iterates over the elements of a given iterable sequence.


for x in ("hello", 5, "world", (9, 3.14)):
print x


hello
5
world
(9, 3.1400000000000001)

This is usually the only thing you need to do with a sequence, to work with the values it contain, but other times you'll need to also know what is the index in said sequence, that's when enumerate is useful.

Btw, why do you want to know what's the index of the first uppercase character?

ghostdog74
March 22nd, 2009, 08:25 AM
>>> import re
>>> print re.search("[A-Z]","aAbxx").end()
2
>>> print re.search("[A-Z]","aabXx").end()
4
>>> print re.search("[A-Z]","aabcX").end()
5
>>> print re.search("[A-Z]","aabcxdTd").end()
7

Sprut1
March 23rd, 2009, 07:15 AM
You can also write an listcomp:



a = "hello World"
result = [i for i,c in enumerate(a) if c.isupper()]
print result
>>> [6]


I'd say this is the python way of doing it.

ghostdog74
March 23rd, 2009, 08:08 AM
>>> a = "hello World"
>>> map(str.isupper,a).index(True)
6
>>>