我正在编写一个简单的 Python for 循环来打印字符串中的当前字符。但是,我无法获得角色的索引。这就是我所拥有的,有人知道在循环中获取角色当前索引的好方法吗?
loopme = 'THIS IS A VERY LONG STRING WITH MANY MANY WORDS!'
for w in loopme:
print "CURRENT WORD IS " + w + " AT CHARACTER "
使用该enumerate()
函数生成索引以及您正在循环的序列的元素:
for index, w in enumerate(loopme):
print "CURRENT WORD IS", w, "AT CHARACTER", index
你想迭代字符或单词吗?
对于单词,您必须先拆分单词,例如
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