如何在Python中获取字符串中字符的位置?


当前回答

使用numpy快速访问所有索引的解决方案:

string_array = np.array(list(my_string))
char_indexes = np.where(string_array == 'C')

其他回答

string.find(character)  
string.index(character)  

也许您想查看一下文档,以找出两者之间的区别。

>>> s="mystring"
>>> s.index("r")
4
>>> s.find("r")
4

“冗长”的方式

>>> for i,c in enumerate(s):
...   if "r"==c: print i
...
4

要得到substring,

>>> s="mystring"
>>> s[4:10]
'ring'

我发现的大多数方法都是指查找字符串中的第一个子字符串。要找到所有的子字符串,您需要处理。

例如:

定义字符串

vars = 'iloveyoutosimidaandilikeyou'

定义子字符串

key = 'you'

定义一个函数,该函数可以找到字符串中所有子字符串的位置

def find_all_loc(vars, key):

    pos = []
    start = 0
    end = len(vars)

    while True: 
        loc = vars.find(key, start, end)
        if  loc is -1:
            break
        else:
            pos.append(loc)
            start = loc + len(key)
            
    return pos

pos = find_all_loc(vars, key)

print(pos)
[5, 24]

当字符串包含重复字符时会发生什么? 从我使用index()的经验来看,对于duplicate,你会得到相同的索引。

例如:

s = 'abccde'
for c in s:
    print('%s, %d' % (c, s.index(c)))

将返回:

a, 0
b, 1
c, 2
c, 2
d, 4

在这种情况下,你可以这样做:

for i, character in enumerate(my_string):
   # i is the position of the character in the string

使用numpy快速访问所有索引的解决方案:

string_array = np.array(list(my_string))
char_indexes = np.where(string_array == 'C')