string find mystery
half.italian at gmail.com
Thu Sep 3 07:45:20 CEST 2009
On Sep 2, 10:10 pm, Helvin <helvin... at gmail.com> wrote:
> 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
> 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
> Does anyone know why this is happening?
> Help much appreciated!
> Very puzzled,
string.find() returns the index at which the given word is found
within the string. If the string is not found it returns -1. So, no
matter what you do, string.find() will evaluate to "True"
You could use it like this: if file_str.find("Geometry") != -1:
but you probably want to use: if "Geometry" in file_str:
More information about the Python-list