How to sort a string with digits and letters (digits before letters) in Python

1 Answer

0 votes
def custom_sort(input_str):
    return "".join(sorted(input_str, key=lambda x: (x, x.isdigit())))

input_str = "d2c4b3a1"
sorted_str = custom_sort(input_str)

print("Custom sorted string:", sorted_str)



'''
run:

Custom sorted string: 1234abcd

'''

 



answered May 27, 2025 by avibootz
...