不使用find方法从字符串中查找字符?

时间:2016-09-12 17:37:55

标签: python string

因为我是新手......不明白为什么它不能正常工作? 期待原因和解决方案以及提示 感谢

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"

3 个答案:

答案 0 :(得分:1)

if flag == x看起来很奇怪。您期待x的价值是什么?

我建议您将flag初始化为None,然后在循环结束时检查它不是None

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"

答案 1 :(得分:0)

你试图让flag成为(第一个)匹配字符索引的位置。好!

if str[x]==find:
  flag = x
  break

但如何判断是否找不到任何东西?针对x的测试无济于事!尝试将flag初始化为可测试的值:

flag = -1
for x in range(0,l):
    if str[x]==find:         
        flag = x
        break

现在一切都很简单:

if flag != -1:
    print "found in index no",flag
else:
    print "not found in there"

答案 2 :(得分:0)

您的搜索方法有效(遍历字符串中的字符)。但是,当您评估是否找到该角色时,问题就在最后。您将flagx进行了比较,但在进行比较时,xout 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"