gpt4 book ai didi

python - 如何按字母顺序对字符串进行排序,小写字母排在大写字母之前?

转载 作者:行者123 更新时间:2023-11-28 19:39:38 24 4
gpt4 key购买 nike

有没有一种简单的方法可以在 python 中对字符串进行排序?

我知道你能做到

string="aCBb"
''.join(sorted(string))

这会将其分类为“BCab”。但是有没有办法让 python 将它排序为“aBbC”?

编辑:为了清楚起见,我的应用程序必须在“B”之后添加“b”,它们不能互换。我的原始解决方案使用 key=str.lower(),按原始顺序返回它们。

最佳答案

如果您需要保证大写字母排在小写字母之前:

>>> ''.join(sorted(string, key=lambda s:(s.lower(), s)))
'aBbC'

>>> ''.join(sorted(sorted(string), key=str.lower))
'aBbC'

关于python - 如何按字母顺序对字符串进行排序,小写字母排在大写字母之前?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20511275/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com