Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegant check for -1 in Python

Tags:

python

string

Is there an elegant way to check for the value -1 as returned by the str.find() instance method ? I find testing for a value of -1 very ugly but I don't want to say < 0 either as that could cause confusion.

if (myString.find('foo') == -1):
    print("foo not found in ", myString)
like image 541
TheMathemagician Avatar asked Sep 26 '26 06:09

TheMathemagician


1 Answers

Don't use str.find() if you don't need the index. Use in to test for the substring instead; or in this case not in to negate the test:

if 'foo' not in myString:
    print("foo not found in", myString)
like image 173
Martijn Pieters Avatar answered Sep 27 '26 19:09

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!