0

I need to look for a substring in a string and if I don't find it, perform an action. So I do this, and it works fine:

if 'AAA' not in myString: 
   print "AAA is not in myString"

What I need, however, is to avoid cases where AAA is a part of XAAA. In other words, I don't want my script to notice any presence of "XAAA" when it does if 'AAA' not in myString. So how can I modify the above if-clause to the following:

if 'AAA' not in myString except for cases where 'AAA' is a part of 'XAAA':
    print "AAA is not in myString"
3
  • 5
    if 'AAA' not in myString.replace('XAAA', ''):? Commented Jul 31, 2017 at 20:08
  • 3
    I'd suggest renaming this question. Something like "How to replace a string conditionally in Python" Commented Jul 31, 2017 at 20:09
  • @AdamHughes Done. Commented Jul 31, 2017 at 20:16

4 Answers 4

8

I like re module solutions

if not re.search(r'(?<!X)AAA', myString):
    ...
Sign up to request clarification or add additional context in comments.

Comments

5

I don't want my script to notice any presence of "XAAA" when it does if 'AAA' not in myString.

You can first remove any occurrences of the sub-string XAAA from myString, and then test if AAA is not a sub-string of myString:

if 'AAA' not in myString.replace('XAAA', ''):
    # do action

1 Comment

I'm not sure this works with XAAAA or AAXAAAA. The question was unclear about this case.
3

There are two ways.

You can remove XAAA from the string then compare:

if 'AAA' not in myString.replace('XAAA', ''):
    # do something

Or you can check for it first then compare:

if 'XAAA' not in myString:
    if 'AAA' not in myString:
        # do something

Two-liner:

if 'XAAA' not in myString and 'AAA' not in myString:
    # do something

Comments

0

Regular expressions might serve you extremely-well here.

For instance, you could match the string against the so-called "regex," /[^X]?AAA/.

This regex tests for the existence of any string AAA which is not preceded by the character X, anywhere in the string.

(The ? is needed to support the possibility that the AAA occurs at the beginning of the string, where no X could possibly precede it.)

Every programming language supports regular expressions ... "and this is why."

(FYI: "regular expressions are an immensely-deep pool of water, that it is very well worth exploring." In practical application, it produces many "practical applications," such as this one, even if all that you ever do is to skim the surface of it and very-happily stay there.)

2 Comments

(This answer, by the way, has been tested ...)
Didn't Gribouillis use regex in his answer though?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.