Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort the letters in a string alphabetically in Python

Tags:

python

string

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

So for:

a = 'ZENOVW'

I would like to return:

'ENOVWZ'
like image 290
Superdooperhero Avatar asked Oct 07 '22 12:10

Superdooperhero


People also ask

How do you sort a string character in alphabetical order in Python?

Use sorted() and str. join() to sort a string alphabetically in Python. Another alternative is to use reduce() method. It applies a join function on the sorted list using the '+' operator.

How do you sort a string alphabetically in Python without sorting?

You can use Nested for loop with if statement to get the sort a list in Python without sort function. This is not the only way to do it, you can use your own logic to get it done.

Can you sort a string Python?

In Python, there are two ways, sort() and sorted() , to sort lists ( list ) in ascending or descending order. If you want to sort strings ( str ) or tuples ( tuple ), use sorted() .


2 Answers

You can do:

>>> a = 'ZENOVW'
>>> ''.join(sorted(a))
'ENOVWZ'
like image 349
K Z Avatar answered Oct 09 '22 00:10

K Z


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

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

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

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

>>> print c
'ENOVWZ'
like image 107
askewchan Avatar answered Oct 09 '22 01:10

askewchan