What's the design thinking behind this?
To me it's easier to do something like
if string.index(substring) > -1:
# do stuff
than trying to catch an exception. If the substring
is not found, at least your program doesn't break.
Someone told me 'returning -1 is a bad pattern'. Why is that?
What is the Pythonic way for checking substring?
The Python "ValueError: substring not found" occurs when we pass a value that doesn't exist in the string to the str. index() method. To solve the error, use the find() method instead, e.g. my_str. find('z') , or handle the error using a try/except block.
Python String rindex() method returns the highest index of the substring inside the string if the substring is found. Otherwise, it raises ValueError.
A Python substring is a portion of text taken from a string. You can extract a substring in Python using slicing, with the format: YourString[StartingIndex:StoppingIndex:CharactersToSkip]. Often, programmers have data that they want to split up into different parts.
The “TypeError: string index out of range” error is raised when you try to access an item at an index position that does not exist. You solve this error by making sure that your code treats strings as if they are indexed from the position 0.
str.index()
throws an exception; you were perhaps thinking of the str.find()
method instead:
if string.find(substring) > -1:
The str.index()
documentation explicitly states this:
Like
find()
, but raiseValueError
when the substring is not found.
However, the correct way to test for substring membership is to use in
:
if substring in string:
Because this way at least the return type of the function is fixed. Also your example is not pythonic, it should read:
if str in string:
# do stuff
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With