Jump to content

Searching a string

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
5 replies to this topic

#1
yamman13

yamman13

    Learning Programmer

  • Members
  • PipPipPip
  • 56 posts
I'm having problems searching through a string, it doesn't seem to ever find the character its looking for, even when I definitely know the character is there.

while count<len(string):

    print string[count]

    if string[count] == ":": #starting point

        start=count

        state=True

    # need to do this after string is found

    if state==True:

        if string[count+3] is not "1" or "2" or "3" or "4" or "5" or "6" or "7" or "8" or "9": #if thers two non numbers, string has stopped

            end=count

                break #so count+2 isnt more than len string

    count+=1




I'm not sure if I should use '==' or 'is', neither seems to be working.

#2
Guest_x42_*

Guest_x42_*
  • Guests
== will work, the problem is that the computer isn't smart enough to figure out "is not 1, or 2, or 3, or 4, etc, etc" it needs something like: "if string[count+3]is not 1 and string[count+3] is not 2 and , etc, etc"

#3
CatatonicMan

CatatonicMan

    Newbie

  • Members
  • PipPip
  • 13 posts
I'd suggest using a set or dictionary to store your 'exclusion' values, then just check if the string is in the set.

For example...


exclusions = set(('1', '2', '3', '4', '5', '6', '7', '8', '9'))

string = 'a1b2c3d4:'

for char in string:

    if char not in exclusions:

        print 'Char not in exclusions!'

    else:

        print 'Char in exclusions!'



#4
Guest_x42_*

Guest_x42_*
  • Guests
I had no idea that you could do that

#5
manux

manux

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 234 posts
Hmm, you don't even need a set, but then maybe a set is faster:
for char in string:
    if char not in "1234567890":
        print "Cheese!"


#6
CatatonicMan

CatatonicMan

    Newbie

  • Members
  • PipPip
  • 13 posts
I was thinking of speed, yes. The set check should resolve in O(1) time, where the string search would require O(n) time.