Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python program to sort strings by substring range
Next article icon

Python Program to Sort a String

Last Updated : 07 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Sorting strings in Python is a common and important task, whether we need to organize letters alphabetically or systematically handle text data. In this article, we will explore different methods to sort a string starting from the most efficient to the least.

Using sorted with join()

sorted() function is the most efficient way to sort a string. It returns a sorted list of characters which we can then join back into a single string. This method is concise and efficient as it uses Python’s built-in functions.

Python
s = "python"  # Sorting the string sorted_string = ''.join(sorted(s)) print(sorted_string) 

Output
hnopty 

Explanation:

  • sorted(text) creates a list of sorted characters from the input string.
  • ‘ ‘.join() combines the sorted characters back into a single string.

Let’s explore different ways to sort a string in Python.

Table of Content

  • Using a Custom Sorting Function
  • Using a For Loop
  • Using a Temporary Data Structure

Using a Custom Sorting Function

If we need more control over the sorting logic, we can use a custom key function with sorted().

Python
s = "python"  # Custom sorting: reverse alphabetical order sorted_string = ''.join(sorted(s, reverse=True)) print(sorted_string) 

Output
ytponh 

Explanation:

  • reverse=True sorts the characters in descending order.
  • Customization Allows sorting based on specific criteria.
  • This method is slightly less efficient due to the custom logic but still uses sorted() efficiently.

Using a For Loop

If we want a manual approach, sorting can be implemented using loops. This is less efficient but helps understand the logic behind sorting.

Python
s = "python"  # Sorting manually sorted_list = list(s) for i in range(len(sorted_list)):     for j in range(i + 1, len(sorted_list)):         if sorted_list[i] > sorted_list[j]:             sorted_list[i], sorted_list[j] = sorted_list[j], sorted_list[i]  sorted_string = ''.join(sorted_list) print(sorted_string) 

Output
hnopty 

Explanation:

  • Nested loops compare and swap characters to arrange them in order.
  • Manual sorting helps understand the sorting process but is less efficient.

Using a Temporary Data Structure

We can use additional data structures, such as dictionaries or counters, to assist in sorting. This approach can be useful in specific scenarios.

Python
s = "python"  # Sorting using a dictionary char_count = {char: s.count(char) for char in s} sorted_string = ''.join(sorted(char_count.keys())) print(sorted_string) 

Output
hnopty 

Explanation:

  • text.count(char) counts occurrences of each character.
  • Sorting keys Sorts characters based on their occurrences or order in the dictionary.
  • This method is less efficient due to the overhead of counting characters.


Next Article
Python program to sort strings by substring range
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python string-programs
  • Python-sort
Practice Tags :
  • python

Similar Reads

  • Python program to sort strings by substring range
    Given a String List, sort by a range of substrings. Input : test_list = ["geeksforgeeks", "best", "geeks", "preparation", "interview"], i, j = 1, 3 Output : ['geeksforgeeks', 'geeks', 'best', 'interview', 'preparation'] Explanation : "eek" < "eek" < "est" < "nte" < "rep". Input : test_li
    5 min read
  • Python program to Sort Strings by Punctuation count
    Given the Strings list, sort by punctuations count. Input : test_list = ["gfg@%^", "is", "Best!"] Output : ['is', 'Best!', 'gfg@%^'] Explanation : 0 < 1 < 3, sorted by punctuation count. Input : test_list = ["gfg@%^", "Best!"] Output : [ 'Best!', 'gfg@%^'] Explanation : 1 < 3, sorted by pun
    3 min read
  • How to sort a list of strings in Python
    In this article, we will explore various methods to sort a list of strings in Python. The simplest approach is by using sort(). Using sort() MethodThe sort() method sorts a list in place and modifying the original list directly. [GFGTABS] Python a = ["banana", "apple", "cher
    2 min read
  • Python program to list Sort by Number value in String
    Given a List of strings, the task is to write a Python program to sort list by the number present in the Strings. If no number is present, they will be taken to the front of the list. Input : test_list = ["gfg is 4", "all no 1", "geeks over 7 seas", "and 100 planets"] Output : ['all no 1', 'gfg is 4
    6 min read
  • Python - Extract Sorted Strings
    Given a String List, extract all sorted strings. Input : test_list = ["hint", "geeks", "fins", "Gfg"] Output : ['hint', 'fins', 'Gfg'] Explanation : Strings in increasing order of characters are extracted.Input : test_list = ["hint", "geeks", "Gfg"] Output : ['hint', 'Gfg'] Explanation : Strings in
    5 min read
  • Reverse Sort a String - Python
    The goal is to take a given string and arrange its characters in descending order based on their Unicode values. For example, in the string "geeksforgeeks", the characters will be sorted from highest to lowest, resulting in a new string like "ssrokkggfeeeee". Let's understand different methods to pe
    2 min read
  • Python | Sort each String in String list
    Sometimes, while working with Python, we can have a problem in which we need to perform the sort operation in all the Strings that are present in a list. This problem can occur in general programming and web development. Let's discuss certain ways in which this problem can be solved. Method #1 : Usi
    4 min read
  • Python - Sort Strings by Maximum ASCII value
    Given strings list, perform sort by Maximum Character in String. Input : test_list = ["geeksforgeeks", "is", "best", "cs"] Output : ["geeksforgeeks", "is", "cs", "best"] Explanation : s = s = s < t, sorted by maximum character. Input : test_list = ["apple", "is", "fruit"] Output : ["apple", "is",
    4 min read
  • Python - Test substring order
    Given two strings, check if substring characters occur in correct order in string. Input : test_str = 'geeksforgeeks', K = 'sees' Output : True Explanation : "s" after that "ee" and then "s" is present in order in string 1. Input : test_str = 'geeksforgeeks', K = 'seef' Output : False Explanation :
    5 min read
  • Python | Alternate Sort in String list
    Sometimes, while working with Python list, we can have a problem in which we need to perform sorting only of alternatively in list. This kind of application can come many times. Let's discuss certain way in which this task can be performed. Method : Using join() + enumerate() + generator expression
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences