You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中使用extend()添加字符串索引时,如何获取实际索引值而非对象引用?

问题描述

我想要遍历一个长字符串,查找指定子串的出现实例,然后创建一个包含每个找到的子串的索引值及子串本身的列表。但目前得到的不是可读的索引数值,而是对象引用,例如[<built-in method index of str object at 0x000001687B01E930>, 'b'],我期望得到[123, 'b']这样的结果。

我尝试的代码如下:

test_string = "abcdefg"
look_for = ["b","f"]
result = []

for each in test_string:
    if each in look_for:
        result.extend([each.index, each])
        
print(result)

我知道可以用列表推导式实现,但之后计划在该for循环中添加更多代码,因此仅询问索引相关问题。我试过str(each.index)和print(str(result)),但均无效果。请问我忽略了什么?

问题原因与解决方法
  1. 核心问题:你用的each.index是单个字符对象的index方法的引用,不是调用方法得到的结果;而且就算写成each.index(),也只能得到这个字符在自身字符串里的索引(永远是0),这不是你要的原字符串中的位置。

  2. 正确做法:遍历字符串时用enumerate函数,它会同时返回每个字符的原字符串索引和字符本身,代码修改如下:

test_string = "abcdefg"
look_for = ["b","f"]
result = []

# 用enumerate拿到索引和字符
for idx, each in enumerate(test_string):
    if each in look_for:
        result.extend([idx, each])
        
print(result)  # 输出: [1, 'b', 5, 'f']

这样就能得到你期望的原字符串索引数值了,后续也可以在这个循环里添加其他逻辑。

内容的提问来源于stack exchange,提问作者OutThere

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 01:05:04