简体   繁体   中英

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. Eg, can I compare characters? Can I find the middle of a string somehow?

I'm using Python 3.4.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM