Instagram
youtube
Facebook
Twitter

A Python Program to Sort Characters of a String in Ascending Order

A Python Program to Sort Characters of a String in Ascending Order

Code Explanation in Points:

  • def ascending_characters(string):
     
    • A function is defined to sort characters of the string in ascending order.
       
  • char_list = list(string)
     
    • Converts the string into a list of characters (since strings are immutable in Python).
       
  • Nested loops (for i and for j)
     
    • These loops go through each character and compare it with the rest.
       
    • If the current character is greater than the next one, they are swapped.
       
  • char_list[i], char_list[j] = char_list[j], char_list[i]
     
    • Swaps the characters to arrange them in ascending (alphabetical) order.
       
  • return ''.join(char_list)
     
    • Converts the sorted list back into a string and returns it.
       
  • Input/Output part:
     
    • Takes string input from the user.
       
    • Calls the function and prints the sorted string.

 

Program:

def ascending_characters(string):

    char_list = list(string)  

    for i in range(len(char_list)):

        for j in range(i + 1, len(char_list)):

            if char_list[i] > char_list[j]:

                char_list[i], char_list[j] = char_list[j], char_list[i]

    return ''.join(char_list)  

string = input("Enter characters: ")

result = ascending_characters(string)

print("String in ascending order:", result)