1

Wondering if there is a simple way to reorder characters in a string in alphabet order?

Saying, if "hello", want it to be "ehllo"? Tried sort method does not exist. If anyone have any great ideas, it will be great.

a = 'hello'
print a.sort()

thanks in advance, Lin

Lin Ma
  • 9,739
  • 32
  • 105
  • 175
  • 1
    `print ''join.sorted('hello')` – R Nar Nov 13 '15 at 23:55
  • @RNar, wondering how ''join.sorted('hello') happened underlying? Seems magic. :) – Lin Ma Nov 13 '15 at 23:57
  • 1
    look at the link. it makes use of `str.join(list)` and `sorted(iterable)` methods – R Nar Nov 13 '15 at 23:58
  • BTW, shall I import some packages in order to use join? I am using Python 2.7.x. – Lin Ma Nov 13 '15 at 23:58
  • 1
    no those are both built in methods – R Nar Nov 13 '15 at 23:58
  • @RNar, it is very smart. Could you help to add an answer? I will mark it as answer to benefit other people. Have a good weekend. :) – Lin Ma Nov 14 '15 at 00:03
  • 1
    I think the first comment had a typo and was supposed to be `print(''.join(sorted("hello")))` – Galax Nov 14 '15 at 00:03
  • 1
    @Galax, yes, that is my bad. because it is python 2, the out most brackets are not necessary but the call to join should be in brackets – R Nar Nov 14 '15 at 00:04
  • 1
    Yes the outer brackets are not needed for Python 2, I didn't see any mention of the Python version though. The typo was the `.` in the wrong place and the missing brackets after `join`. – Galax Nov 14 '15 at 00:06

1 Answers1

3

Try this:

a = 'hello'
a = ''.join(sorted(a))
print a

It should return 'ehllo'.

Here's a similar post about the same problem: How to sort the letters in a string alphabetically in Python

Community
  • 1
  • 1
Brian
  • 78
  • 1
  • 1
  • 6