Python Error?

I used the find attribute and got

a=‘dog’
a.find( ‘og’)
result is 1

a.find(‘k’)
result is -1

Which makes sense -1 means doesn’t contain the character 1 means it does, but when I use it the find attribute for numbers and anything with a dash in it, I get a value greater than 1.

b= ‘dog-cat’
b.find( ‘at’)
result is 5

‘dog-cat’.find( ‘at’)
result is 5

‘2008-2009’.find( ‘2009’)
result is 5

num=‘2008-2009’

num.find( ‘2009’)
result is 5

num.find( ‘32’)
result is -1

Why do I get a value greater than 1 when the character is found but only a -1 when the value is not.

Also, I getting 0 when the character are within the string? Am I doing something wrong or is this an issue with Python.

‘2008-2009’.find( ‘20’)
result is 0

‘2008-2009’.find( ‘2’)
result is 0

num.find( ‘2’)
result is 0

num.find( ‘20’)
result is 0

I tend to use “in” rather than find:


>>> temp = "200-20-80"
>>> "20" in temp
True
>>> "2" in temp
True
>>> "82" in temp
False

-1 is returned when the element is not found, as you mentions.

The number returned (0,1,5,etc.) is the place in the string where the start of the element was found.

In “dog”, “og” started at element 1 (d is 0).
In “dog-cat”, “at” started at 5.

Right, that’s how that string method is designed. From:

string.find(s, sub[, start[, end]])Return the lowest index in s where the substring sub is found such that sub is wholly contained in s[start:end]. Return -1 on failure.

[QUOTE=Carlo890;6589]
Why do I get a value greater than 1 when the character is found but only a -1 when the value is not.

Also, I getting 0 when the character are within the string? Am I doing something wrong or is this an issue with Python.

‘2008-2009’.find( ‘20’)
result is 0

‘2008-2009’.find( ‘2’)
result is 0

num.find( ‘2’)
result is 0

num.find( ‘20’)
result is 0[/QUOTE]

0 is the first found index of your search, to get the second ‘2’ you can use rfind, which should return 5.

num.rfind(‘2’)

[QUOTE=Carlo890;6589]
a=‘dog’
a.find( ‘og’)
result is 1
[/QUOTE]

If you changed the 2nd line to a.find(‘g’), you’ll get 2 because it is in the 2nd element of the string. String indexes atart at 0. Using dashes or numbers in your string doesn’t change the expected output of the function.

[QUOTE=Adam Pletcher;6592]Right, that’s how that string method is designed. From:

string.find(s, sub[, start[, end]])Return the lowest index in s where the substring sub is found such that sub is wholly contained in s[start:end]. Return -1 on failure.[/QUOTE]

I read that when I found the find attribute but I did not understand what it meant, or better yet didn’t read it thorough enough to understand it… thank you all for the help

[QUOTE=supertom44;6590]I tend to use “in” rather than find:


>>> temp = "200-20-80"
>>> "20" in temp
True
>>> "2" in temp
True
>>> "82" in temp
False

[/QUOTE]

That seems pretty useful I never thought of using in for something like that or at all really. Thank you for the help