occvtech
occvtech

Reputation: 463

Python - Create tuple only if values are even

I have a working set of code that iterates through a string and searches for 2 relevant substrings. (shoutout to user @bulbus for the help!)

The code returns a list of tuples containing the index positions for the location of the next instance of each substring.

For example, if the strings and substrings looked like this:

sub_A = "StringA"
sub_B = "StringB"

s = "abcdefStringAghijklStringB"

Then the code returns the tuple (6,19) because that is the next index position where the two strings exist.

The relevant part of the code looks like this:

[(m.start(),re.compile(sub_b).search(s,m.start()).start()) for m in re.finditer(sub_A,s)]

However, I want to change the code so that it only returns values to the tuple if the value is even. I.E. in my example above the value "19" should not be a valid return.

As an example, let's say this is my new string:

xxStringAStringBStringB

I want the tuple to return (2,16). Because those are the next "valid" returns.

My code currently returns (2,9) but I want to skip the "StringB" at index 9 since it is an odd number.

Thoughts? And thanks!!

Upvotes: 0

Views: 148

Answers (1)

kaza
kaza

Reputation: 2327

>>> s = "abcdefStringAghijklStringB"                                                                
>>> [(m.start(),next((x.start() for x in re.compile(sub_B).finditer(s,m.start()) if x.start()%2==0),None)) for m in re.finditer(sub_A,s)]
[(6, None)]
>>> s='xxStringAStringBStringB'                                                                     
>>> [(m.start(),next((x.start() for x in re.compile(sub_B).finditer(s,m.start()) if x.start()%2==0),None)) for m in re.finditer(sub_A,s)]
[(2, 16)]
  1. We use finditer to find all the sub_B after sub_A, but we need to bailout on first condition(even position) that satisfies
  2. To do that we use next() call to bail out of the iteration. Read here for more.
  3. Now if we do not find a sub_B we want the iteration to return a default value in this case we chose None

Upvotes: 1

Related Questions