Python:如何按字母顺序排列字符串中的字母,以区分大写字母和小写字母(Python: How to sort the letters in a string alphabetically keep

编程入门 行业动态 更新时间:2024-10-27 01:31:20
Python:如何按字母顺序排列字符串中的字母,以区分大写字母和小写字母(Python: How to sort the letters in a string alphabetically keeping distinction between uppercases and lowercases)

我试图以一种特定的方式排列字符串的单词:在我的代码下面的输出是“MNWdeorwy”,但我希望它是“deMNorWwy” (所以我需要保持字母顺序,尽管是上层o lowercases)你能帮我理解我错在哪里,为什么? 谢谢

wrd = "MyNewWord" def order_word(s): if s == "": return "Invalid String!" else: c = sorted(s) d = ''.join(sorted(c)) return d print order_word(wrd)

我想确切地说我的问题与以下不同: 如何在Python中按字母顺序排列字符串中的字母 :实际上,链接中给出的答案没有考虑字符串中上下字符串之间的区别。

I am trying to order the words of a string in a particular way: In my code below the output is "MNWdeorwy" but i would like it to be "deMNorWwy" (so i need to keep the letters ordered despite being upper o lowercases) Could you please help me to understand where I am wrong and why? Thank you

wrd = "MyNewWord" def order_word(s): if s == "": return "Invalid String!" else: c = sorted(s) d = ''.join(sorted(c)) return d print order_word(wrd)

I would like to precise that my question is different from the following: How to sort the letters in a string alphabetically in Python : in fact, the answers given in the link does not consider the difference between upper and lowercases in a string.

最满意答案

sorted()根据每个字符的序数排序。 大写字母的序号低于全部小写字母。 如果你想要不同的行为,你需要定义你自己的密钥:

c = sorted(s, key=lambda c: (c.lower(), c.islower()))

这样, c将按('c', 1)排序, C按('c', 0)排序。 两者都出现在('d', ...)或('e', ...)等之前,但大写字母c比小写字母c更早(更低)。

顺便说一句,你不应该说d = "".join(sorted(c))因为c已经被排序。 只要做d = "".join(c)

sorted() sorts based off of the ordinal of each character. Capital letters have ordinals that are lower than all lowercase letters. If you want different behavior, you'll need to define your own key:

c = sorted(s, key=lambda c: (c.lower(), c.islower()))

That way, c would be sorted by ('c', 1) and C is sorted by ('c', 0). Both come before ('d', ...) or ('e', ...) etc., but the capital C is earlier (lower) than the lowercase c.

By the way, you shouldn't say d = "".join(sorted(c)) because c has already been sorted. Just do d = "".join(c)

更多推荐

本文发布于:2023-07-31 20:06:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1347302.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字母   大写字母   字符串   顺序排列   sort

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!