Search code examples
pythonstringalphabetical

Check if a word is between two other words, by alphabetical order


I want to check if a given word is between two other words, by alphabetical (or "dictionary") order.

For example:

word1 = 'feelgoodlab'
word2 = 'elainedilley'
check = 'feelingfat'

I want to see if check is between word1 and word2 (it is).

I tried this:

word1 = 'feelgoodlab'
word2 = 'elainedilley'
check = 'feelingfat'

print(check >= word1 and check <= word2)

but that's giving me False.


Solution

  • Well you here basically check if:

    word1 <= check <= word2
    

    But here, it is the opposite: word2 is less, and word1 is greater, we can however compbine the two possibilities with:

    word1 <= check <= word2 or word2 <= check <= word1
    

    So here regardless of what the order is between word1 and word2, it checks if check is "sandwiched" in between.