w3resource

Python: Sort a string lexicographically


Sort string lexicographically.

Write a Python program to sort a string lexicographically.

Python String Exercises: Sort a string lexicographically

Sample Solution:

Python Code:

# Define a function named lexicographic_sort that takes one argument, 's'.
def lexicographic_sort(s):
    # Use a nested sorting approach:
    # 1. First, sort the characters of the string 's' in ascending order.
    # 2. Then, sort the sorted characters based on their uppercase representations (case-insensitive).
    return sorted(sorted(s), key=str.upper)

# Call the lexicographic_sort function with different input strings and print the results.
print(lexicographic_sort('w3resource'))  # Output: '3ceeorrsuw'
print(lexicographic_sort('quickbrown'))  # Output: 'biknqorwuc' 

Sample Output:

['3', 'c', 'e', 'e', 'o', 'r', 'r', 's', 'u', 'w']                                                            
['b', 'c', 'i', 'k', 'n', 'o', 'q', 'r', 'u', 'w'] 

For more Practice: Solve these Related Problems:

  • Write a Python program to sort the characters of a string in lexicographical order using the sorted() function.
  • Write a Python program to convert a string into a sorted list of its characters and then join them back into a string.
  • Write a Python program to implement lexicographical sorting of a string without using the built-in sorted() function.
  • Write a Python program to use recursion to sort the characters of a string lexicographically.

Go to:


Previous: Write a Python function to convert a given string to all uppercase if it contains at least 2 uppercase characters in the first 4 characters.
Next: Write a Python program to remove a newline in Python.

Python Code Editor:

Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.