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

2024-09-19 23:31:05 发布

您现在位置:Python中文网/ 问答频道 /正文

因为我是个新手。。。不明白为什么它不能正常工作? 期待的原因和解决办法,并提示 谢谢

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"

Tags: inif原因findflaggramprintfound
3条回答

您的搜索方法是有效的(遍历字符串中的字符)。然而,你的问题是在最后当你评估你是否找到了这个角色。你在比较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"

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"

您正试图使flag成为(第一个)匹配字符的索引位置。很好!你知道吗

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

但是如果什么也没找到怎么说呢?测试x也没用!尝试将标志初始化为可测试值:

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"

相关问题 更多 >