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

1 Answer

0 votes
import re

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

input_str = "d2c4b3a1"
sorted_str = custom_sort(input_str)

print("Custom sorted string:", sorted_str)

 
 
 
'''
run:
 
Custom sorted string: abcd1234
 
'''

 



answered May 26, 2025 by avibootz
...