Search code examples
pythonlogiccontrol-flow

In python, test for 1 or 3 consecutive instances of a string, but not 2 (without regex)


I am dealing with data in which...

* marks property A
** marks property B
*** marks properties A & B

text1 = "spam*eggs"   # A
text2 = "eggs**spam"  # B
text3 = "spam***spam" # A & B

Testing for property B is easy,

"**" in <string>

but testing for property A with the same strategy would give a false positive with text2.

>>> "*" in text2
True

I want to test for property A. Is there a pythonic way to do this without using regular expressions? I don't want to use regex because I share code with beginner programmers who are not familiar with it.


Solution

  • It is not clear if you want to just test for Property A, as in the text, or A or C, as in the title. (C being A and B)

    To just get True or False for 1 or 3 and not 2, you can use a code rephrasing of your logic:

    result = '***' in x or (not  '**' in x and '*' in x)
    

    To get the letter of ABC out depending on the pattern:

    result = ['None','A','B','C'][('*' in x) + ('**' in x) + ('***' in x)]
    

    To just test for Property A (one star) without failing on two or three. (EDIT: simplified this. If ** is not there then neither is ***):

    isItA = '*' in x and not  '**' in x