python - 如何在没有重复结果的情况下从python中的字符串获取索引位置
问题描述
在 a 的 for 循环中string
,我想获取该index
特定字母在 that 中的位置string
,但如果该单词中有相同的字母,则它不起作用。
我遍历了 中的字母,string
并获得了字母的index
位置(通过使用.find()
or .index()
)以获取string
由唯一字母组成的 a ,但如果string
包含相同的字母,则索引将只是出现在 中的第一个字母的位置string
。
indexList = [] #list of stored indexes
word = "grocery" #could be any string, just using "grocery" as an example
for letter in word:
index = word.find(letter)
indexList.append(index)
print (indexList)
#Expected output: [0, 1, 2, 3, 4, 5, 6]
#Actual output: [0, 1, 2, 3, 4, 1, 6]
5 和 1index
位置具有相同的字母(“r”),因此.find()
and.index()
方法只是添加 1 而不是 5,因为它是string
. 我想知道是否有任何方法可以获取指定字母在单词中的位置。请帮忙。谢谢!
解决方案
Find
接受两个可选参数:(start
默认为 0)和end
(默认为字符串结尾 - 适合您的情况)。使用 enumerate 包括起点:
for i, letter in enumerate(word):
index = word.find(letter, i)
indexList.append(index)
推荐阅读
- amazon-web-services - 如何在 AWS 中打包和提供 Web 应用程序
- django-rest-framework - django rest api中唯一的用户名而不是唯一的电子邮件
- laravel - 在服务提供者引导方法中注册路由时未初始化身份验证
- sails.js - 如何将上传文件通过管道传输到另一台服务器
- sql - 列值更改时 SQL 重置 row_number
- javascript - 在烧瓶应用程序中添加 javascript 函数影响
- php - 在 PHP 中维护 MySQL 选择中的正斜杠
- javascript - 是否可以获取 Firebase Cloud Firestore 数据库中可用的集合的文档 ID?
- django - Django 中间件 process_template_response 显示中间件响应然后查看响应
- python-sphinx - 从 genindex.html 中删除诸如“(xyz 方法)”和“(xyz 中的类)”之类的文本