Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: how to ignore 'substring not found' error

Let's say that you have a string array 'x', containing very long strings, and you want to search for the following substring: "string.str", within each string in array x.

In the vast majority of the elements of x, the substring in question will be in the array element. However, maybe once or twice, it won't be. If it's not, then...

1) is there a way to just ignore the case and then move onto the next element of x, by using an if statement?

2) is there a way to do it without an if statement, in the case where you have many different substrings that you're looking for in any particular element of x, where you might potentially end up writing tons of if statements?

like image 399
simply_helpful Avatar asked Apr 14 '26 04:04

simply_helpful


2 Answers

You want the try and except block. Here is a simplified example:

a = 'hello'
try:
    print a[6:]
except:
    pass

Expanded example:

a = ['hello', 'hi', 'hey', 'nice']
for i in a:
    try:
        print i[3:]
    except:
        pass

lo
e
like image 66
sshashank124 Avatar answered Apr 16 '26 18:04

sshashank124


You can use list comprehension to filter the list concisely:

Filter by length:

a_list = ["1234", "12345", "123456", "123"]
print [elem[3:] for elem in a_list if len(elem) > 3]
>>> ['4', '45', '456']

Filter by substring:

a_list = ["1234", "12345", "123456", "123"]
a_substring = "456"
print [elem for elem in a_list if a_substring in elem]
>>> ['123456']

Filter by multiple substrings (Checks if all the substrings are in the element by comparing the filtered array size and the number of substrings):

a_list = ["1234", "12345", "123456", "123", "56", "23"]
substrings = ["56","23"]
print [elem for elem in a_list if\
             len(filter(lambda x: x in elem, substrings)) == len(substrings)]
>>> ['123456']
like image 22
Bora Caglayan Avatar answered Apr 16 '26 19:04

Bora Caglayan