简体   繁体   English

为什么我在 Python 中遇到字符串索引问题

[英]why Im having String indexing problem in Python

I'm trying to understand why I'm having the same index again when I apply .index or .find why I'm getting the same index '2' again why not '3'?我试图理解为什么当我应用 .index 或 .find 时我再次拥有相同的索引,为什么我再次获得相同的索引“2”,为什么不是“3”? when a letter is repeated, and what is the alternative way to get an index 3 for the second 'l'当一个字母重复时,获得第二个“l”的索引 3 的替代方法是什么

text = 'Hello'
for i in text:
    print(text.index(i))

the output is:输出是:

0
1
2
2
4

It's because .index() returns the lowest or first index of the substring within the string.这是因为.index()返回字符串.index()字符串的最低第一个索引。 Since the first occurrence of l in hello is at index 2, you'll always get 2 for "hello".index("l") .由于lhello第一次出现在索引 2 处,因此"hello".index("l")总是会得到 2。

So when you're iterating through the characters of hello , you get 2 twice and never 3 (for the second l ).因此,当您遍历hello的字符时,您会得到 2 两次而永远不会得到 3(对于第二个l )。 Expanded into separate lines, it looks like this:展开成单独的行,它看起来像这样:

"hello".index("h")   # = 0
"hello".index("e")   # = 1
"hello".index("l")   # = 2
"hello".index("l")   # = 2
"hello".index("o")   # = 4

Edit: Alternative way to get all indices :编辑:获取所有索引的替代方法

One way to print all the indices (although not sure how useful this is since it just prints consecutive numbers) is to remove the character you just read from the string:打印所有索引的一种方法(虽然不确定这有多有用,因为它只打印连续的数字)是删除您刚刚从字符串中读取的字符:

removed = 0
string = "hello world"    # original string
for char in string:
  print("{} at index {}".format(char, string.index(char) + removed))  # index is index() + how many chars we've removed
  string = string[1:]    # remove the char we just read
  removed +=1            # increment removed count
text = 'Hello'
for idx, ch in enumerate(text):
    print(f'char {ch} at index {idx}')  

output输出

char H at index 0
char e at index 1
char l at index 2
char l at index 3
char o at index 4

If you want to find the second occurance, you should search in the substring after the first occurance如果你想找到第二次出现,你应该在第一次出现后的子串中搜索

text = 'Hello'
first_index = text.index('l')
print('First index:', first_index)

second_index = text.index('l', first_index+1) # Search in the substring after the first occurance
print('Second index:', second_index)

The output is:输出是:

First index: 2
Second index: 3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM