Re: shouldn't 'string'.find('ugh') return 0, not -1 ?



On Oct 31, 9:31 am, jelle <jelleferi...@xxxxxxxxx> wrote:
the subject pretty much says it all.
if I check a string for for a substring, and this substring isn't found,
should't the .find method return 0 rather than -1?
this breaks the

if check.find('something'):
do(somethingElse)

idiom, which is a bit of a pity I think.

string.find has always been kind of a wart in Python; that's why
they're getting rid of it. For testing for the presence of a
substring, use the in operator:

if "something" in check:
do(somethingElse)

When you need the position of a substring, using the index methods:

i = check.index("something")

index returns an exception of the substring is not there, so no need
to worry about what it returns.

Finally, it really won't kill you to do this:

if check.find("something") >= 0:
do(somethingElse)


Carl Banks


.



Relevant Pages

  • Re: [QUIZ] Longest Repeated Substring (#153)
    ... My hack at the substring problem is based on suffix ... in the original string. ... def initialize ...
    (comp.lang.ruby)
  • Favicon type detection - possible?
    ... this is my cobbled together browser detection ... {string: navigator.userAgent, ... subString: "OmniWeb", ... {// for newer Netscapes ...
    (comp.lang.javascript)
  • Comments on Comments (was Re: Getting to 100 (#119))
    ... # yield each partitioning of the receiver into count partitions ... # an initial substring of increasing length, ... # the string into count-1 partitions. ... #:ops - an array of strings representing the operators to be inserted into ...
    (comp.lang.ruby)
  • Re: Computability and logic
    ... as regards a mathematical formulation of a substring ... substring in a string with another substring? ... result of substituting a term for a variable in a formula'. ... As I recall, he doesn't get into replacing term for term, ...
    (sci.logic)
  • Re: "Reversed" LCS problem
    ... have to worry so much about defining "substring" versus "subsequence," ... say "the letters in the string must be next to each other, ... >> has the lowest number of common characters from the other strings, ... > No whitespaces, no sequences, only substrings. ...
    (comp.programming)