keelsinit
keelsinit

Reputation: 33

Searching for capital letters within a string

I am trying to find all of the capital letters within a string, and output what that characters element in the array is. For example:

"PiE" would have an out put of [0, 2]

What I have noticed is that if there were two of the same capital letters, is would show as the same elements. i.e:

"HaH" has an output of [0,0] 

Here is my code this far:

import re

pattern = re.compile(r'^[A-Z\d]+$')
elemList = []

def capitals(word):
    pattern.match(word)
    for w in word:
        if w != w.lower():
            a = word.index(w)
            elemList.append(a)
    return elemList

Thanks, guys!

Upvotes: 0

Views: 86

Answers (4)

Hippolippo
Hippolippo

Reputation: 813

This is a simple solution:

output = []
for i in range(text):
    if text[i].upper() == text[1]:
        output.append(i)
print(output)

I think that will work. It might not be the best way but it was the first idea that came into my head.

Upvotes: -1

Thomas Weller
Thomas Weller

Reputation: 59302

The following seems to be a straight forward approach using "normal" programming concepts:

def getUpperPositions(str):
    positions = []
    currentPosition = 0
    for c in str:
        if c.isupper():
            positions.append(currentPosition)
        currentPosition += 1
    return positions

print(getUpperPositions("HaH"))

Upvotes: 0

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

With re.finditer() function:

import re

s = ' ..HaH soME text heRe ...'
upper_pos = [m.start() for m in re.finditer(r'[A-Z]', s)]
print(upper_pos)

The output:

[3, 5, 9, 10, 19]

https://docs.python.org/3.6/library/re.html?highlight=re#re.finditer

Upvotes: 0

Orenshi
Orenshi

Reputation: 1873

You can use a list comprehension here. How's this?

elemList = [i for i, letter in enumerate(word) if letter.isupper()]

Here it is in a repl:

>>> def find_capitals(word):
...     return [i for i, letter in enumerate(word) if letter.isupper()]
...
>>> find_capitals('PiE')
[0, 2]
>>> find_capitals('HaHaHa')
[0, 2, 4]

Upvotes: 2

Related Questions