str = "gram chara oi ranga matir poth"
find ='p'
l = len(str)
for x in range(0,l):
if str[x]==find:
flag = x
#break
if flag == x:
print "found in index no",flag
else:
print "not found in there"
您的搜索方法是有效的(遍历字符串中的字符)。然而,你的问题是在最后当你评估你是否找到了这个角色。你在比较flag和x,但是当你做比较时,x是out of scope。因为x是在for循环语句中声明的,所以它只在for循环中定义。因此,要修复代码,请为flag设置一个可以检查的初始值,然后更改结尾处的检查:
flag = None
for x in range(len(str)):
if str[x] == find:
flag = x
break # Using break here means you'll find the FIRST occurrence of find
if flag:
print "found in index no",flag
else:
print "not found in there"
flag = None # assign a "sentinel" value here
str = "gram chara oi ranga matir poth"
find = 'p'
for x in range(len(str)):
if str[x] == find:
flag = x
# Leaving out the break is also fine. It means you'll print the
# index of the last occurrence of the character rather than the first.
break
if flag is not None:
print "found in index no", flag
else:
print "not found in there"
您的搜索方法是有效的(遍历字符串中的字符)。然而,你的问题是在最后当你评估你是否找到了这个角色。你在比较
flag
和x
,但是当你做比较时,x
是out of scope。因为x
是在for循环语句中声明的,所以它只在for循环中定义。因此,要修复代码,请为flag
设置一个可以检查的初始值,然后更改结尾处的检查:if flag == x
看起来很奇怪。你希望x
的值是多少?你知道吗我建议将
flag
初始化为None
,然后在循环的末尾检查它是否不是None
。你知道吗您正试图使flag成为(第一个)匹配字符的索引位置。很好!你知道吗
但是如果什么也没找到怎么说呢?测试x也没用!尝试将标志初始化为可测试值:
现在一切都很简单:
相关问题 更多 >
编程相关推荐