Michi
Michi

Reputation: 125

How do I sort a string in alphabetical order in Python?

I know there is a sort function:

>>> a = 'bags'
>>> ''.join(sorted(a))
'abgs'

However, I need to write mine from scratch. I think I would like to use mergesort but I'm not sure how that would work for a string in Python. E.g., can I compare characters? Can I find the middle of a string somehow?

I'm using Python 3.4.

Upvotes: 0

Views: 6012

Answers (1)

mattgathu
mattgathu

Reputation: 1147

Yes you could compare characters.

b > a evaluates to True in Python, and so forth.

You could first convert the string to a list, and get it's middle via its length, do sequential comparison and then join the sorted list to get back a sorted string.

Upvotes: 1

Related Questions