string find mystery

Hendrik van Rooyen hendrik at microcorp.co.za
Thu Sep 3 08:17:33 EDT 2009


On Thursday 03 September 2009 07:10:37 Helvin wrote:
> Hi,
>
> I have come across this very strange behaviour. Check this code:
>
>         if file_str.find('Geometry'):
>         #if file_str.endswith('Data_Input_Geometry.txt'):
>             print 'I found geometry'
>         elif file_str.find('Material'):
>             print 'I found material'
> The amazing thing is when file_str  = 'C:\Qt\SimLCM\Default
> \Data_Input_Material.txt',
> the first if statement if fulfilled, that seemingly says that in this
> file_str, python actually finds the word 'Geometry'.
> I know this, because the line: 'I found geometry' is printed. However,
> if instead of using file_str.find(), I use file_str.endswith(), it
> does not exhibit this strange behaviour.
>
> Obviously, I want the elif line to be true, instead of the first if
> statement.
>
> Does anyone know why this is happening?
> Help much appreciated!

The interactive Interpreter is your friend:

s = "a;kljghkahklahdfgkjahdfhadafjd;l"
s.find("banana")
-1
bool(_)
True

- Hendrik





More information about the Python-list mailing list