dppham1 dppham1 - 1 month ago 7
Python Question

Sorting strings with numbers in Python

I have this string:

string = '9x3420aAbD8'


How can I turn string into:

'023489ADabx'


What function would I use?

Answer

You can just use the built-in function sorted to sort the string lexographically. It takes in an iterable, sorts each element, then returns a sorted list. Per the documentation:

sorted(iterable[, key][, reverse])

Return a new sorted list from the items in iterable.

You can apply that like so:

>>> ''.join(sorted(string))
'023489ADabx'

Since sorted returns a list, like so:

>>> sorted(string)
['0', '2', '3', '4', '8', '9', 'A', 'D', 'a', 'b', 'x']

Just join them together to create the desired string.

Comments