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


当前回答

如果你想找到第一个匹配。

Python有一个内置的字符串方法来完成这项工作:index()。

string.index(value, start, end)

地点:

值:(必选)要搜索的值。 start:(可选)从哪里开始搜索。默认值为0。 end:(可选)结束搜索的位置。Default是到字符串的末尾。

def character_index():
    string = "Hello World! This is an example sentence with no meaning."
    match = "i"
    return string.index(match)
        
print(character_index())
> 15

如果你想找到所有的匹配项。

假设你需要所有字符匹配的索引,而不仅仅是第一个。

python的方法是使用enumerate()。

def character_indexes():
    string = "Hello World! This is an example sentence with no meaning."
    match = "i"

    indexes_of_match = []

    for index, character in enumerate(string):
        if character == match:
            indexes_of_match.append(index)
    return indexes_of_match

print(character_indexes())
# [15, 18, 42, 53]

或者更好的是一个列表理解:

def character_indexes_comprehension():
    string = "Hello World! This is an example sentence with no meaning."
    match = "i"

    return [index for index, character in enumerate(string) if character == match]


print(character_indexes_comprehension())
# [15, 18, 42, 53]

其他回答

more_itertools。Locate是一个第三方工具,用于查找满足条件的项目的所有索引。

这里我们找到了字母“i”的所有索引位置。

鉴于

import more_itertools as mit


text = "supercalifragilisticexpialidocious"
search = lambda x: x == "i"

Code

list(mit.locate(text, search))
# [8, 13, 15, 18, 23, 26, 30]

有两个字符串方法,find()和index()。两者之间的区别在于当没有找到搜索字符串时会发生什么。find()返回-1,index()引发ValueError。

使用find ()

>>> myString = 'Position of a character'
>>> myString.find('s')
2
>>> myString.find('x')
-1

使用指数()

>>> myString = 'Position of a character'
>>> myString.index('s')
2
>>> myString.index('x')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: substring not found

来自Python手册

字符串。Find (s, sub[, start[, end]]) 返回s中子字符串sub所在位置的最低索引,使得sub完全包含在s[start:end]中。失败时返回-1。负值的开始和结束以及解释的默认值与切片相同。

And:

字符串。索引(s, sub[, start[, end]]) 类似于find(),但在未找到子字符串时引发ValueError。

>>> 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'

当字符串包含重复字符时会发生什么? 从我使用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

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

例如:

定义字符串

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]