Search code examples
pythonstring-comparison

How can a comparison operator be used with a[i:] < b[i:]?


Reading some Python code, I discovered this syntax if a[i:] < b[j:] and the colon threw me for a loop. I found this great question/answer about it:

Colon (:) in Python list index

But then I looked back at my code example, and it's still unclear how it's using what I understand to be a shortcut for splice in a comparison.

I'm attempting to reverse engineer this into a JavaScript equivalent function. That weird comparison is the only thing I can't comprehend. What exactly is python comparing? String length? or something else?

def combineStrings(a, b):
    answer = ''
    a += '~'
    b += '~'
    i = 0
    j = 0
    while a[i] != '~' or b[j] != '~':
        print (i, a[i:], b[j:], a[i:] < b[j:])
        if a[i] != '~' and a[i:] < b[j:]:
            answer += a[i]
            i += 1
        else:
            answer += b[j]
            j += 1
    print (answer)

combineStrings('TACO', 'CAT')

Output

0 TACO~ CAT~ False
0 TACO~ AT~ False
0 TACO~ T~ True
1 ACO~ T~ True
2 CO~ T~ True
3 O~ T~ True
4 ~ T~ False
CATACOT

Solution

  • It's comparing by Lexicographical Order

    If you're trying to find the character in b (T) that is as least as big as a (T) and insert all the consecutive letters in a (A, C, O) that are smaller that character in b, this code makes sense.

    ~ is the biggest printable ASCII character (126), hence it's used as a comparison.

    0 TACO~ AT~ False # because 'T' < 'A'
    0 TACO~ T~ True   # because '~' > 'A'