2

I have this string:

string = '9x3420aAbD8'

How can I turn string into:

'023489ADabx'

What function would I use?

2 Answers 2

3

You can just use the built-in function sorted to sort the string lexicographically. 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.

Sign up to request clarification or add additional context in comments.

1 Comment

This is the best and only way to do it.
1

You can use the sorted() function to sort the string, but this will return a list

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

to turn this back into a string you just have to join it, which is commonly done using ''.join()

So, all together:

sorted_string = ''.join(sorted(string))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.