Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ValueError: Substring not found when using str.index

I am a beginner in python and the following code I am trying

input_number = raw_input("Please input the number:")
print type(input_number)
if(input_number.index('0')):
    print "Not Accepted"
else:
    print "Accepted"

When I am giving the input for example '1234506' its showing "Not accepted" which is valid but when I am giving '123456' its throwing error "Substring not found". So how can I print the else part.

like image 764
Chinmoy Avatar asked Sep 12 '25 03:09

Chinmoy


2 Answers

when you enter 123456 or 1234506, python considers it as a string.

Now, when you use string_object.index(substring), it looks for the occurrence of substring (in your case, the substring is '0') in the string_object. If '0' is present, the method returns the index at which the substring is present, otherwise, it throws an error.

you can use the following instead :

if '0' in input_number :
    print 'not accepted'
else :
    print 'accepted'
like image 164
Tushar Aggarwal Avatar answered Sep 14 '25 18:09

Tushar Aggarwal


str.index errors out when there is no match. In this situation, you can either choose to handle the error, or use str.find instead which returns an integer value between -1 and len(input_number), or do a set membership test on the original string.

Option 1

Conversion to set lookup:

if '0' not in set(input_number):
    print "Accepted"
else:
    print "Not accepted"

Option 2

Using try...except to handle the ValueError.

try:
    input_number.index('0')
    print "Not accepted"

except ValueError:
    print "Accepted"

Option 3

Using str.find:

if input_number.find('0') < 0:
    print "Accepted"
else:
    print "Not accepted"
like image 27
cs95 Avatar answered Sep 14 '25 17:09

cs95