如何在字符串中查找下一个相似字母的索引
How to find index of next similar letter in a string
a = "programming in python is Fun"
a.find("i") = 8
它returns "i"
在 a.
中第一次出现的索引
是否可以找到第二个 "i"
的索引?
您可以使用 enumerate()
with list comprehension 查找所有索引:
s = "programming in python is Fun"
my_char = "i"
my_indexes = [i for i, x in enumerate(s) if x == my_char]
# where `my_indexes` holds:
# [8, 12, 22]
这里my_char
是你要查找索引的字符。 my_indexes
是一个列表,其中包含每次在字符串中找到 my_char
的索引。详情请参考enumerate()
document。
因此,您可以访问第二次出现的索引:
>>> my_indexes[1]
12
find()
也有一个可选的起始索引,您可以将其用作:
a = "programming in python is Fun"
first = a.find('i')
print(a.find('i',first+1))
您还可以通过以下方式使用numpy
:
import numpy as np
a = "programming in python is Fun"
x = np.frombuffer(a.encode(), dtype=np.uint8)
np.where(x == ord('i')) # (array([ 8, 12, 22]),)
使用 np.frombuffer
reinterpret str as a char buffer and then using np.where
will return all the indices that will match the character you are interested in (or more accurately the integer representing the Unicode character, using ord
).
a = "programming in python is Fun"
a.find("i") = 8
它returns "i"
在 a.
中第一次出现的索引
是否可以找到第二个 "i"
的索引?
您可以使用 enumerate()
with list comprehension 查找所有索引:
s = "programming in python is Fun"
my_char = "i"
my_indexes = [i for i, x in enumerate(s) if x == my_char]
# where `my_indexes` holds:
# [8, 12, 22]
这里my_char
是你要查找索引的字符。 my_indexes
是一个列表,其中包含每次在字符串中找到 my_char
的索引。详情请参考enumerate()
document。
因此,您可以访问第二次出现的索引:
>>> my_indexes[1]
12
find()
也有一个可选的起始索引,您可以将其用作:
a = "programming in python is Fun"
first = a.find('i')
print(a.find('i',first+1))
您还可以通过以下方式使用numpy
:
import numpy as np
a = "programming in python is Fun"
x = np.frombuffer(a.encode(), dtype=np.uint8)
np.where(x == ord('i')) # (array([ 8, 12, 22]),)
使用 np.frombuffer
reinterpret str as a char buffer and then using np.where
will return all the indices that will match the character you are interested in (or more accurately the integer representing the Unicode character, using ord
).