Search code examples
pythoncompareasciistring-comparisonalphabetical

How to compare strings in python that also contains other ascii symbols like underscores?


I have a list of strings, make it two for this example:

list = ["ACTVN_Cars", "ACT_CFR_AD"]

Then i try to check if the list is sorted alphabetically with this code:

test.verify(list[0].lower() <= list[1].lower())

And with that i run into an error. Why does the test work other strings, but not for this one? And what would be a good way to test the list?


Solution

  • Can't seem to reproduce, can you share your test.verify() code:

    list = ["ATVN_Cars", "ACT_CFR_AD"]
    list[0] < list[1]
    >>> False
    list[0] > list[1]
    >>> True
    list[0].lower() > list[1].lower()
    >>> True
    

    Answering your other question the easiest way to "test" something is with assert

    assert list[0] > list[1] is True
    

    Regarding the _ character:

    ord("_")
    >>> 95
    ord("a")
    >>> 97
    ord("A")
    >>> 65
    
    So: 
    "A" < "_" < "a"
    >> True