jubibanna
jubibanna

Reputation: 1185

Elegant way to find a specific text in python

Is there a more beautiful way to exclude strings from a text than this? Sorry I am fairly new to programming. For example, I want to find bettext[1] by searching through the list of strings.

bettext[0] = '1. HL Over + / Under'
bettext[1] = 'Over + / Under'
bettext[2] = 'H2 Over + / Under'

excl_str_1 = "1. HL Over + / Under"
excl_str_2 = "2. HL Over + / Under"
excl_str_3 = "corners"
excl_str_4 = "yellow cards"
excl_str_5 = "1st"
excl_str_6 = "H2"


if not (excl_str_1) in bettext:
    if not (excl_str_2) in bettext:
        if not (excl_str_3) in bettext:
            if not (excl_str_4) in bettext:
                if not (excl_str_5) in bettext:
                    if not (excl_str_6) in bettext:
                        if (search_str) in bettext:
                            print(bettext)

Sorry if it's already been answered, I tried two different but similar stackoverflow answers and tried to apply them to this code but it didn't work

Upvotes: 2

Views: 129

Answers (3)

timgeb
timgeb

Reputation: 78690

First of all, use a container for your strings, not n variables. I suggest a set because in checks will run in constant time.

string_check = {"1. HL Over + / Under", "2. HL Over + / Under", "corners", ...}

(The set contains excl_str_1, excl_str_2, ..., search_str.)

Next, use the any builtin:

if not any(s in string_check for s in bettext):
    # do something

This is roughly equivalent to:

for s in bettext:
    if s in string_check:
        break
else:
    # do something

The for/else may look weird. Mind-parse it as for/nobreak.

Upvotes: 1

Moberg
Moberg

Reputation: 5503

Yes there is!

For starters, put all the excluded strings in a list because you are going to do the same thing with them. Then use all to make sure something is true for every item of this list:

excl_strings = ["1. HL Over + / Under", "2. HL Over + / Under", "corners", "yellow cards", "1st", "H2"

if all(excl_string not in bettext for excl_string in excl_strings):
   if search_str in bettext:
       print(bettext)

Upvotes: 1

user2390182
user2390182

Reputation: 73460

There are utils to shorten your code, particularly you can use a list of strings to exclude and all or any with a generator expression in your condition:

excl_strings = ["1. HL Over + / Under",
                "2. HL Over + / Under",
                "corners",
                "yellow cards",
                "1st",
                "H2"]

if search_str in bettext and not any(s in bettext for s in excl_strings):
    print(bettext)

Upvotes: 1

Related Questions