gpt4 book ai didi

python - 从字符串末尾开始的字符索引

转载 作者:太空宇宙 更新时间:2023-11-03 18:09:43 27 4
gpt4 key购买 nike

我知道要从字符串末尾获取字符的索引,您可以:

    str.index(sub, -1)

那么为什么当我调用这段代码时会产生错误呢?

    def test(string):
for letter in string:
print string.index(letter, -1)

谢谢。

最佳答案

I know that to get the index of a character from the end of a string, ...

我想你可能会感到困惑,它不是从字符串末尾获取索引,而是从字符串的开始获取索引,但是仅从给定索引开始搜索

如果您输入并运行以下代码,这一点就会变得明显:

def test(string):
for letter in 'e':
print string.index(letter, -1)

test("abcde")

并且您正确地得到了 4 作为输出,即 e 从字符串开始的位置。

在您的代码(以及上面的示例)中,我们告诉它从索引 -1 开始搜索子字符串,这只是字符串中的最后一个字符.

因此,如果您的字符串是 "abc",它会首先在子字符串 "c" 中查找 a,但不会找到它会引发异常。

将代码更改为:

def test(string):
for letter in string:
print string.index(letter)
test("abcde")

将为您提供正确的索引不会引发异常。

如果您确实需要从字符串末尾开始的索引(因此e0并且a4),一些简单的数学运算就可以做到:

def test(string):
for letter in string:
print len(string) - string.index(letter, 0) - 1
test("abcde")

此代码为您提供字母 ae:

4
3
2
1
0

关于python - 从字符串末尾开始的字符索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26227233/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com