简体   繁体   English

在字符串中搜索大写字母

[英]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. 我正在尝试查找字符串中的所有大写字母,并输出数组中的character元素是什么。 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. 我注意到的是,如果有两个相同的大写字母,它将显示为相同的元素。 ie: 即:

"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! 多谢你们!

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]

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"))

With re.finditer() function: 使用re.finditer()函数:

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 https://docs.python.org/3.6/library/re.html?highlight=re#re.finditer

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. 这可能不是最好的方法,但这是我想到的第一个想法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM