【发布时间】:2014-02-06 01:12:11
【问题描述】:
我最近有一个项目,我需要找到用户输入的字符串中出现特定字符的所有索引。 例如,用户输入字符串“这是一个测试”,我想找到字符串中所有 t 的索引,我会得到 0、11、14 我查看了内置命令,但找不到任何东西,所以知道找到它的方法会很有帮助。
【问题讨论】:
标签: python-3.x
我最近有一个项目,我需要找到用户输入的字符串中出现特定字符的所有索引。 例如,用户输入字符串“这是一个测试”,我想找到字符串中所有 t 的索引,我会得到 0、11、14 我查看了内置命令,但找不到任何东西,所以知道找到它的方法会很有帮助。
【问题讨论】:
标签: python-3.x
使用enumerate 和列表理解:
st="This is a test"
print([i for i, c in enumerate(st) if c.lower()=='t'])
或者:
print([i for i, c in enumerate(st) if c in 'tT'])
在任何一种情况下,打印:
[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
使这项工作的第二件事是枚举,它将字符串中所有字符的计数添加为一个元组:
>>> 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
【讨论】:
只是一种直接的方法作为(更好的)enumerate 选项的替代方案:
[range(len(st))[i] for i in range(len(st)) if st[i].lower() == 't']
【讨论】: