华为机考入门python3--(26)牛客26-字符串排序

分类:字符串

知识点:

  1. 字符串是否仅由字母构成    my_str.isalpha()

  2. 字母列表按小写排序    letters.sort(key=lambda x: x.lower())

题目来自【牛客】

图片

def custom_sort(input_str):
    letters = []
    non_letters = []
    for char in input_str:
        if char.isalpha():
            letters.append(char)
        else:
            non_letters.append(char)

    # lambda x: x.lower() 是一个匿名函数,它接受参数 x(这里代表列表中的每个字母)并返回一个小写形式的 x。
    # 因此,通过传递 key=lambda x: x.lower(),可以确保在排序时不区分字母大小写。
    letters.sort(key=lambda x: x.lower())

    # 新的字符串
    result = ''
    for char in input_str:
        # 如果是字符则从已排序列表中取出第一个
        if char.isalpha():
            result += letters.pop(0)
        else:
            result += non_letters.pop(0)
            
    return result

# input_str = "Type"
# print(custom_sort(input_str))  # 输出:'epTy'

# input_str = "BabA"
# print(custom_sort(input_str))  # 输出:'aABb'

# input_str = "By?e"
# print(custom_sort(input_str))  # 输出:'Be?y'

input_str = input().strip()
print(custom_sort(input_str))

猜你喜欢

转载自blog.csdn.net/u013288190/article/details/139100698