Alphabetical Letter Sorting with Non-Letter Characters Preserved

  • Share this:

Code introduction


This function sorts the letters in the input string in alphabetical order while keeping non-letter characters in their original positions.


Technology Stack : re library (for regular expressions), string library (for string operations)

Code Type : String processing

Code Difficulty : Intermediate


                
                    
def aordify_string(s):
    """
    将字符串中的字母按照字典顺序排序,非字母字符保持原位。

    :param s: 输入的字符串
    :return: 字母排序后的字符串
    """
    import re
    import string

    def sort_letters(match):
        return ''.join(sorted(match.group()))

    return re.sub('([a-zA-Z]+)', sort_letters, s)