Python 3.x 如何在python中查找字符串中特定字符(不计数)的数值集

Python 3.x 如何在python中查找字符串中特定字符(不计数)的数值集,python-3.x,Python 3.x,我最近得到了一个项目,在这个项目中,我需要找到用户输入的字符串中出现特定字符的所有索引。 例如,用户输入字符串“thisatest”,我想找到字符串中所有t的索引,我将得到0、11、14 我查看了内置命令,但找不到任何内容,因此了解查找此命令的方法将非常有帮助。使用和列表理解: st="This is a test" print([i for i, c in enumerate(st) if c.lower()=='t']) 或: 无论哪种情况,打印: [0, 10, 13] 解释 “使

我最近得到了一个项目,在这个项目中,我需要找到用户输入的字符串中出现特定字符的所有索引。 例如,用户输入字符串“thisatest”,我想找到字符串中所有t的索引,我将得到0、11、14 我查看了内置命令,但找不到任何内容,因此了解查找此命令的方法将非常有帮助。

使用和列表理解:

st="This is a test"

print([i for i, c in enumerate(st) if c.lower()=='t'])
或:

无论哪种情况,打印:

[0, 10, 13]

解释

“使这一点起作用”的第一件事是字符串在Python中是可移植的:

>>> st="This is a test"
>>> for c in st:
...    print c
... 
T
h
i
s

i
s

a

t
e
s
t
第二件事是enumerate,它将字符串中所有字符的计数添加为元组:

>>> for tup in enumerate(st):
...    print tup
... 
(0, 'T')
(1, 'h')
(2, 'i')
(3, 's')
(4, ' ')
(5, 'i')
(6, 's')
(7, ' ')
(8, 'a')
(9, ' ')
(10, 't')
(11, 'e')
(12, 's')
(13, 't')
将这两个概念合并到一个列表中会产生以下结果:

[i for i, c in enumerate(st) if c.lower()=='t']
                 ^^^                               Produces the tuple of index and character
       ^  ^                                        Index, Character
                                  ^^^^^^^^^^^      test the character if it is 't'
 ^                                                 What is wanted - list of indices

作为(更好的)
枚举
选项的替代方案,这是一种简单的方法:

[range(len(st))[i] for i in range(len(st)) if st[i].lower() == 't']

谢谢你,这帮了我很大的忙。谢谢你,这很有效,你能解释一下它为什么有效吗?我想了解代码背后的工作原理
[range(len(st))[i] for i in range(len(st)) if st[i].lower() == 't']