我正在编写一个简单的Python for循环来修改字符串中的当前字符。但是,我无法获得角色的索引。这就是我所拥有的,有没有人知道在循环中获取字符当前索引的好方法?
loopme = 'THIS IS A VERY LONG STRING WITH MANY MANY WORDS!'
for w in loopme:
print "CURRENT WORD IS " + w + " AT CHARACTER "
答案 0 :(得分:77)
使用enumerate()
function生成索引以及要循环的序列元素:
for index, w in enumerate(loopme):
print "CURRENT WORD IS", w, "AT CHARACTER", index
答案 1 :(得分:4)
你想迭代字符或单词吗?
对于单词,您必须首先拆分单词,例如
for index, word in enumerate(loopme.split(" ")):
print "CURRENT WORD IS", word, "AT INDEX", index
这将打印单词的索引。
对于绝对角色位置,你需要像
这样的东西chars = 0
for index, word in enumerate(loopme.split(" ")):
print "CURRENT WORD IS", word, "AT INDEX", index, "AND AT CHARACTER", chars
chars += len(word) + 1