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


当前回答

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

其他回答

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

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]
string.find(character)  
string.index(character)  

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

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

只是为了完成,在这种情况下,我想在一个文件名中找到扩展名,以便检查它,我需要找到最后一个'。,在这种情况下使用rfind:

path = 'toto.titi.tata..xls'
path.find('.')
4
path.rfind('.')
15

在我的情况下,我使用以下,无论完整的文件名是什么工作:

filename_without_extension = complete_name[:complete_name.rfind('.')]

为了完整起见,如果你需要找到字符串中某个字符的所有位置,你可以这样做:

s = 'shak#spea#e'
c = '#'
print([pos for pos, char in enumerate(s) if char == c])

这将打印:[4,9]