我正在尝试编写一个代码,该代码将返回字母 c 首次出现的索引,如果 c 不在字符串中,则返回 None 。到目前为止,这是我想出的:
def find_c(f):
z = 0
c_pos = None
while c_pos is None or z < len(f):
if f[z] == 'c' or f[z] == 'C':
c_pos = z
z += 1
return c_pos
但无论我输入什么字符串,我的输出总是无。有什么帮助吗?
如果您仍想使用 while 循环,则在找到第一个 'C' 的索引后,您可能只想返回该索引,而不是遍历字符串的其余部分。
def find_c(f):
z = 0
while z < len(f):
if f[z] == 'c' or f[z] == 'C':
return z # Returns first index where it finds 'c'
z += 1
return None # Return None if never found
然而,比使用 while 循环更简单的方法是使用 for 循环枚举值。您还可以使用该.lower()
功能使字符小写,这样您只需'c'
像提到的其他评论者一样进行比较。
改用 for 循环:
def find_c(f):
for index, char in enumerate(f):
if char.lower() == 'c':
return index # Returns first index where it finds 'c'
return None # Return None if never found (reached end of string)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句