How to Sort letters alphabetically in a string in Python

In this tutorial, we will learn how to Sort letters alphabetically in a string in Python

      Sort letters alphabetically in a string in Python

Code and Explanation :

def code(s):
    # Sort the string using sorted() and join the sorted characters back into a string
    return ''.join(sorted(s))

# Prompt the user to enter a string
str1 = input("Enter a string: ")

# Print the original string entered by the user
print("Original string:", str1)

# Sort the string using the function
result = code(str1)

# Print the sorted string
print("Sorted string:", result)

Here’s how the code works:

  • EXPLATION OF FUNCTION
    1. The function ‘code(s)‘ takes a single argument ‘s‘, which is expected to be a string.
    2. Inside the function, ‘sorted(s)‘ sorts the characters of the string ‘s‘ in alphabetical order.
    3. The ‘sorted(s)‘ function returns a list of characters, so ‘ ”.join(sorted(s))‘ is used to join these characters back into a single string.
    4. The sorted string is then returned by the function.
  • Taking user input as a string and storing in variable ‘str1′.
  • Printing the original string.
  • Sort the string alphabetically by using the function ‘code(s)’ and storing in variable ‘result‘.
  • Printing the alphabetically sorted string.

Sample Output :-

  • Enter a string: codespeedy
  • Original string: codespeedy
  • Reversed string: cddeeeopsy

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top