Python Program to Sort characters in a String

[1755 views]




This is one of the popular questions asked to freshers in their interview questions. If you are planning to give a Python Developer Interview for fresher, you must definitely know this. In the code, you are asked to take an input String from user and then sort all the characters in the String in ascending order.

Python Code to Sort Characters in String:

#take input from the user string = input("Enter string - ") #converting input string into list of characters charList=list(string) #sorting elements of list sortedChar=''.join(sorted(charList)) print("After Sorting String in ascending order : ", sortedChar)

Output:

Enter string - pointers After Sorting String in ascending order : einoprst

Explanation:

For the input string "pointers", we convert the string into list of characters. So it becomes -
['p','o','i','n','t','e','r','s']

Then we simply use the sorted() function of python to arrange the characters in ascending order. So, after that it becomes -
['e','i','n','o','p','r','s','t']

                 






Comments










Search Anything:

Sponsored Deals ends in



Technical Quizzes Specially For You:

Search Tags

    Sort alphabets in a string using python