如何在Python中按字母顺序对字符串中的字母进行排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15046242/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 13:10:58  来源:igfitidea点击:

How to sort the letters in a string alphabetically in Python

pythonstring

提问by Superdooperhero

Is there an easy way to sort the letters in a string alphabetically in Python?

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

So for:

因此对于:

a = 'ZENOVW'

I would like to return:

我想返回:

'ENOVWZ'

采纳答案by K Z

You can do:

你可以做:

>>> a = 'ZENOVW'
>>> ''.join(sorted(a))
'ENOVWZ'

回答by askewchan

>>> a = 'ZENOVW'
>>> b = sorted(a)
>>> print b
['E', 'N', 'O', 'V', 'W', 'Z']

sortedreturns a list, so you can make it a string again using join:

sorted返回一个列表,因此您可以使用join以下命令再次使其成为字符串:

>>> c = ''.join(b)

which joins the items of btogether with an empty string ''in between each item.

将 的项目b''每个项目之间的空字符串连接在一起。

>>> print c
'ENOVWZ'

回答by Radek

Sorted() solution can give you some unexpected results with other strings.

Sorted() 解决方案可以为您提供其他字符串的意外结果。

List of other solutions:

其他解决方案列表:

Sort letters and make them distinct:

对字母进行排序并使它们不同:

>>> s = "Bubble Bobble"
>>> ''.join(sorted(set(s.lower())))
' belou'

Sort letters and make them distinct while keeping caps:

对字母进行排序并使它们不同,同时保持大写:

>>> s = "Bubble Bobble"
>>> ''.join(sorted(set(s)))
' Bbelou'

Sort letters and keep duplicates:

对字母进行排序并保留重复项:

>>> s = "Bubble Bobble"
>>> ''.join(sorted(s))
' BBbbbbeellou'

If you want to get rid of the space in the result, add strip() function in any of those mentioned cases:

如果您想去掉结果中的空格,请在上述任何一种情况下添加 strip() 函数:

>>> s = "Bubble Bobble"
>>> ''.join(sorted(set(s.lower()))).strip()
'belou'

回答by Saquib

You can use reduce

您可以使用减少

>>> a = 'ZENOVW'
>>> reduce(lambda x,y: x+y, sorted(a))
'ENOVWZ'

回答by Kanan Joshi

the code can be used to sort string in alphabetical order without using any inbuilt function of python

该代码可用于按字母顺序对字符串进行排序,而无需使用 python 的任何内置函数

k = input("Enter any string again ")

k = input("再次输入任意字符串")

li = []
x = len(k)
for i in range (0,x):
    li.append(k[i])

print("List is : ",li)


for i in range(0,x):
    for j in range(0,x):
        if li[i]<li[j]:
            temp = li[i]
            li[i]=li[j]
            li[j]=temp
j=""

for i in range(0,x):
    j = j+li[i]

print("After sorting String is : ",j)

回答by Mono

Really liked the answer with the reduce() function. Here's another way to sort the string using accumulate().

真的很喜欢 reduce() 函数的答案。这是使用accumulate() 对字符串进行排序的另一种方法。

from itertools import accumulate
s = 'mississippi'
print(tuple(accumulate(sorted(s)))[-1])

sorted(s) -> ['i', 'i', 'i', 'i', 'm', 'p', 'p', 's', 's', 's', 's']

sorted(s) -> ['i', 'i', 'i', 'i', 'm', 'p', 'p', 's', 's', 's', 's' ]

tuple(accumulate(sorted(s)) -> ('i', 'ii', 'iii', 'iiii', 'iiiim', 'iiiimp', 'iiiimpp', 'iiiimpps', 'iiiimppss', 'iiiimppsss', 'iiiimppssss')

元组(累积(排序(s))->('i','ii','iii','iii','iiiim','iiiimp','iiiimpp','iiiimpps','iiiimppss','iiiimppsss ', 'iiiimppsss')

We are selecting the last index (-1) of the tuple

我们正在选择元组的最后一个索引 (-1)

回答by Priyank Arora

Python functionsortedreturns ASCII based result for string.

Python 函数sorted返回基于 ASCII 的字符串结果。

INCORRECT: In the example below, eand dis behind Hand Wdue it's to ASCII value.

不正确:在下面的例子中,e并且d是落后HW由于它以ASCII值。

>>>a = "Hello World!"
>>>"".join(sorted(a))
' !!HWdellloor'

CORRECT: In order to write the sorted string withoutchanging the case of letter. Use the code:

正确:为了在改变字母大小写的情况下编写排序后的字符串。使用代码:

>>> a = "Hello World!"
>>> "".join(sorted(a,key=lambda x:x.lower()))
' !deHllloorW'

If you want to remove all punctuation and numbers. Use the code:

如果要删除所有标点符号和数字。使用代码:

>>> a = "Hello World!"
>>> "".join(filter(lambda x:x.isalpha(), sorted(a,key=lambda x:x.lower())))
'deHllloorW'