Search code examples
pythonpython-3.xif-statementstring-matchingboolean-logic

How do I use boolean logic to make this if-statement more concise in python 3?


I want to extract job titles that consist of either "back-end", "back end" or "backend" from json data of a website. I managed to do so with the following code:

if "back-end" in jobtitle.lower():
            print(jobtitle)
if "back end" in jobtitle.lower():
            print(jobtitle)
if "backend" in jobtitle.lower():
            print(jobtitle)
else:
            continue

The example output is as below:

Software Back-End Developer
(Senior) Back-end PHP Developer
Backend Developer (m/w/d)
Back End Developer
Front-End / Back-End Developer (m/w/d)

How do I make it more concise?


Solution

  • Do you have to use if ... in? Another solution would be to use regular expressions

    back[\-\s]?end Try it here

    Explanation:

    • back: Match "back"
    • [\-\s]: Any of these characters: - or <whitespace>
    • ?: Zero or one of the previous
    • end: Match "end"

    Run it in Python like so:

    rexp = re.compile(r"back[\s\-]?end", re.IGNORECASE)
    if re.search(rexp, jobtitle):
        print(jobtitle)