[英]Checking if index in a string is a certain letter
I want to make a list, that contains indices, that tell me where in a string a certain character is.我想制作一个包含索引的列表,告诉我某个字符在字符串中的位置。
So far i have this:到目前为止,我有这个:
def function(string):
a = []
for i in string:
if string[i] == '*':
a.append(i)
and i get an error: string indices must be integers.我得到一个错误:字符串索引必须是整数。
I searched how to fix this, but couldn't find any suitable answers.我搜索了如何解决这个问题,但找不到任何合适的答案。
So remember that when you loop over an iterator the value of i takes on each element in the iterable.所以请记住,当你遍历一个迭代器时,i 的值会出现在迭代器中的每个元素上。
So if we had:所以如果我们有:
for i in "Hello":
print(i)
Then we would get "H", "e", "l", "l", "o".然后我们会得到“H”、“e”、“l”、“l”、“o”。
These strings cannot be used to index a string.这些字符串不能用于索引字符串。 Instead compare i directly with *而是直接将 i 与 * 进行比较
def function(string):
a = []
for index, character in enumerate(string):
if character == '*':
a.append(index)
The enumerate function counts each iteration枚举 function 计数每次迭代
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.