How to sort a string in the order: lowercase letters - uppercase letters - odd digits - even digits in Python

1 Answer

0 votes
"""
We want to sort characters in this strict order:
1. lowercase letters   (a–z)
2. uppercase letters   (A–Z)
3. odd digits          (1,3,5,7,9)
4. even digits         (0,2,4,6,8)

Strategy:
---------
Assign each character a "category rank" and sort by:
    (category rank, natural character order)

Python's built‑in sorted() with a custom key function
is the idiomatic and efficient way to do this.
"""

def category(c):
    """Return category rank for sorting. Lower rank = earlier."""
    if c.islower():
        return 0  # lowercase
    if c.isupper():
        return 1  # uppercase
    if c.isdigit():
        d = int(c)
        return 2 if d % 2 == 1 else 3  # odd → 2, even → 3
    return 4  # fallback (should not happen for alphanumeric input)

def sort_alphanumeric(s):
    """
    Sort characters using a tuple key:
        (category rank, natural character order)
    """
    return ''.join(sorted(s, key=lambda ch: (category(ch), ch)))

# Usage
s = "a2B3cD8f1Z0"
result = sort_alphanumeric(s)
print("Sorted result:", result)



"""
run:

Sorted result: acfBDZ13028

"""

 



answered 12 hours ago by avibootz

Related questions

...