dppham1 dppham1 - 1 year ago 127
Python Question

Sorting strings with numbers in Python

I have this string:

string = '9x3420aAbD8'

How can I turn string into:


What function would I use?

Answer Source

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))

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download