python - 如何获取字符串中同一字符多次出现的索引?

标签 python regex string

<分区>

我有这个函数接收一个单词并列出每个大写字母的索引:

def capitals(word):
    print word
    lst = []
    for i in word:
        if i.isupper():
            lst += [word.index(i)]
    return lst

word中所有大写字母都不一样时,运行正常。示例:

capitals("AuIkkdjsiP") returns [0,2,9]

但是,如果一个字符串有重复的大写字母,就会发生这种情况:

capitals("AuAskdjfIsjUsdhA") returns [0,0,10,0]

如何在迭代字符串时获取字符“A”其他出现的索引?

最佳答案

你想要enumerate要处理重复字符,您还可以使用 list comprehension :

def capitals(word):
    return [i for i, ch in enumerate(word) if ch.isupper()]

ch是单词中的每个字符,i是字符的索引。

另一方面,如果您想将单个项目添加到列表中,则不应附加+=,如果您要添加多个元素,则+=/extend 是有意义的 但对于单个元素只需附加 :

def capitals(word):
    print word
    lst = []
    for i,ch in enumerate(word):
        if ch.isupper():
            lst.append(i)
    return lst

关于python - 如何获取字符串中同一字符多次出现的索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31908627/

相关文章:

python - 使用 Bokeh 的对数标度上标指数

python - 我可以在 Windows 下更改 python ttk 组合框的颜色吗?

python - 希伯来语和英语字符串之间的分隔

arrays - 字符串不能被强制转换为 Fixnum

python - 在 Python 中从字符串创建字典

python - 计算特定跨度的 pandas 数据框中的累积和

Python,尝试异常(exception),打印错误行#

正则表达式:可选,后跟否定前瞻

正则表达式仅匹配字母

json - libcurl 获取 JSON 字符串