1

As I am a newbie ... not understanding why it's not working properly ? expecting the cause and solution and also tips thanks

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"
martineau
  • 119,623
  • 25
  • 170
  • 301
MASBHA NOMAN
  • 145
  • 1
  • 11

3 Answers3

2

if flag == x looks strange. What value of x are you expecting there?

I'd suggest instead initializing flag to None and then checking for it not being None at the end of the loop.

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"
user94559
  • 59,196
  • 6
  • 103
  • 103
  • thanks, my intention was that if `str[x] == find` then save the index in `flag` my mistake was ....... the value of x is changing..in for loop – MASBHA NOMAN Sep 17 '16 at 10:32
1

You're trying to have flag be the location of the index of the (first) matching character. Good!

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

But how to tell if nothing was found? Testing against x won't help! Try initializing flag to a testable value:

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

Now everything is easy:

if flag != -1:
    print "found in index no",flag
else:
    print "not found in there"
MMN
  • 576
  • 5
  • 7
1

Your method of searching is valid (iterating through the characters in the string). However, your problem is at the end when you're evaluating whether or not you've found the character. You're comparing flag to x, but when you do the comparison, x is out of scope. Because x is declared in a for loop statement, it's only defined inside that for loop. So, to fix your code set an initial value for flag that you can check against, then change the check at the end:

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"
Community
  • 1
  • 1