Sort characters of a string in Python

In this tutorial, we are going to discuss on how to sort characters of the string based on first alphabet symbols followed by digits in Python. When the string contains alphanumeric characters i.e combination of alphabet and digit. For example, if a string is “a2b4c6“, our output should be “abc246“. Let’s discuss how it can be done.

Python methods required for sorting

We are going to use these Python methods in our program for sort characters of the string.

  • isalpha(): To check if the string contains any alphabet characters such as “A-Z” or “a-Z”
  • append(): To appends an element to end of the list. An element of any type (string, number etc.)
  • sorted(): To returns a sorted list of the specified iterable object.

Have a good look at the example code given below:

Python program to sort a string

string='a2b4c6'
alpha=[]
digit=[]
for c in the string:
    if c.isalpha():
        alpha.append(c)
    else:
        digit.append(c)
result=''.join(sorted(alpha)+sorted(digit))
print(result)

OUTPUT:

abc246

CODE EXPLANATION:

Here we have taken a string ‘a2b4c6‘ which is stored in a string variable. Then we used two lists for separate out alphabet and string, by using isalpha() method we got alphabets in one list and digits in other. By using the sorted method we sort out both list then joined both lists using join() method. After printing result, we got our expected output.

Sort string which is given by the user

There is an only declaration difference in which we have to take input string from the user instead of a predefined string.

Have a good look at the example code given below:

 

string=input("Enter a string: ")
alpha=[] 
digit=[] 
for c in string:
    if c.isalpha():
        alpha.append(c)  
    else:
        digit.append(c)
result=''.join(sorted(alpha)+sorted(digit)) 
print(result)

OUTPUT:

Enter a string: a2b4c6
abc246

I hope now you are familiar with the concept and able to solve problems like this.

Read also:

Leave a Reply