Python:遍历字符串但需要知道当前字符的索引
Python: iterate through string but need to know index of current character
我正在遍历一个字符串,如果给定字符的索引号等于某个值,我需要执行某些操作。但是我不确定在迭代期间跟踪当前索引号的最佳方法。例如,我需要大致执行以下操作的代码:
def myfunc(word):
for n in word:
if n[index] = 0:
do this
elif n[index] = 4:
do this
else:
do this
我似乎找不到任何允许我跟踪当前迭代索引的内置计数器或函数。我可以在变量中添加一个计数器,在每个循环之后只添加一个计数器,但这看起来很笨重,我本以为 Python 会知道“n”的当前迭代次数并可以报告回来?
遍历索引而不是元素:
def myfunc(word):
for n in range(len(word)):
if word[n][index] = 0:
do this
elif word[n][index] = 4:
do this
else:
do this
这样,你要的索引就是n
有两种方法可以做到这一点。在 0
和 str:
的 len
之间迭代索引 i
for i in range(len(word)):
c = word[i]
或使用 python 的枚举函数同时执行这两项操作:
for i, c in enumerate(word):
...
def myfunc(word):
new_str = "" #null string
for i, c in enumerate(word): #creates a series of tuples, each on contains index# and current character
if i==0 or i==3:
new_str = new_str + c.upper() #add the character to new_str but make uppercase
else:
new_str = new_str + c #just add the existing lowercase character
return new_str
def myfunc(word):
for index in range(len(word)):
if (index==0):
do this
elif (index==4):
do this
else:
do this
我正在遍历一个字符串,如果给定字符的索引号等于某个值,我需要执行某些操作。但是我不确定在迭代期间跟踪当前索引号的最佳方法。例如,我需要大致执行以下操作的代码:
def myfunc(word):
for n in word:
if n[index] = 0:
do this
elif n[index] = 4:
do this
else:
do this
我似乎找不到任何允许我跟踪当前迭代索引的内置计数器或函数。我可以在变量中添加一个计数器,在每个循环之后只添加一个计数器,但这看起来很笨重,我本以为 Python 会知道“n”的当前迭代次数并可以报告回来?
遍历索引而不是元素:
def myfunc(word):
for n in range(len(word)):
if word[n][index] = 0:
do this
elif word[n][index] = 4:
do this
else:
do this
这样,你要的索引就是n
有两种方法可以做到这一点。在 0
和 str:
len
之间迭代索引 i
for i in range(len(word)):
c = word[i]
或使用 python 的枚举函数同时执行这两项操作:
for i, c in enumerate(word):
...
def myfunc(word):
new_str = "" #null string
for i, c in enumerate(word): #creates a series of tuples, each on contains index# and current character
if i==0 or i==3:
new_str = new_str + c.upper() #add the character to new_str but make uppercase
else:
new_str = new_str + c #just add the existing lowercase character
return new_str
def myfunc(word):
for index in range(len(word)):
if (index==0):
do this
elif (index==4):
do this
else:
do this