Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Python throw an error when a substring is not found?

Tags:

python

string

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?

like image 702
melonccoli Avatar asked Sep 18 '14 15:09

melonccoli


People also ask

How does Python handle substring not found?

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.

Which function in string raises error when the substring is not found?

Python String rindex() method returns the highest index of the substring inside the string if the substring is found. Otherwise, it raises ValueError.

How does substring work in Python?

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.

How do you fix a string index out of range 1 in Python?

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.


2 Answers

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 raise ValueError when the substring is not found.

However, the correct way to test for substring membership is to use in:

if substring in string:
like image 83
Martijn Pieters Avatar answered Oct 13 '22 06:10

Martijn Pieters


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
like image 40
llogiq Avatar answered Oct 13 '22 08:10

llogiq