Python | Ways to sort letters of string alphabetically

Given a string of letters, write a python program to sort the given string in an alphabetical order.

Example:

Input : PYTHON Output : HNOPTY Input : Geeks Output : eeGks

Naive Method to sort letters of string alphabetically

Here we are converting the string into list and then finally sorting the entire list alphabet wise.

Python3

s = "GEEKSFORGEEKS" for i in range ( 0 ,l): li.append(s[i]) for i in range ( 0 ,l): for j in range ( 0 ,l): li[i],li[j] = li[j],li[i] for i in range ( 0 ,l):

Output:

EEEEFGGKKORSS

Using sorted() with join() to sort letters of string alphabetically

Here we are converting the string into a sorted list and then finally joining them using join function.

Python3

# Python3 program to sort letters # of string alphabetically def sortString( str ): return ''.join( sorted ( str )) # Driver code str = 'PYTHON' print (sortString( str ))

Output:

HNOPTY

Using sorted() with accumulate() to sort letters of string alphabetically

Here we are importing accumulate from itertools module converting the string into a sorted list, and hence return the result

Python3

# Python3 program to sort letters # of string alphabetically from itertools import accumulate def sortString( str ): return tuple (accumulate( sorted ( str )))[ - 1 ] # Driver code str = 'PYTHON' print (sortString( str ))

Output:

HNOPTY

Using sorted() with reduce() to sort letters of string alphabetically

Another alternative is to use reduce() method. It applies a join function on the sorted list using ‘+’ operator.

Python3

# Python3 program to sort letters # of string alphabetically from functools import reduce def sortString( str ): return reduce ( lambda a, b : a + b, sorted ( str )) # Driver code str = 'PYTHON' print (sortString( str ))

Output:

HNOPTY

When string is in different cases –

Using sorted() with join() to sort letters of string alphabetically

Here we are converting the string into a sorted list and then finally joining them using the lambda functions.

Python3

# Python3 program to sort letters # of string alphabetically from itertools import accumulate def sortString( str ): return "".join( sorted ( str , key = lambda x:x.lower())) # Driver code str = 'Geeks' print (sortString( str ))

Output:

eeGks

Time Complexity: O(n*logn), as sorted() function is used.
Auxiliary Space: O(n), where n is length of string.

Like Article -->

Please Login to comment.

Similar Reads

Python | Sort the list alphabetically in a dictionary

In Python Dictionary is quite a useful data structure, which is usually used to hash a particular key with value, so that they can be retrieved efficiently. Let's see how to sort the list alphabetically in a dictionary. Sort a List Alphabetically in PythonIn Python, Sorting a List Alphabetically is a typical activity that takes on added interest wh

3 min read Python | Sort the items alphabetically from given dictionary

Given a dictionary, write a Python program to get the alphabetically sorted items from given dictionary and print it. Let’s see some ways we can do this task. Code #1: Using dict.items() C/C++ Code # Python program to sort the items alphabetically from given dictionary # initialising _dictionary dict = 1 min read Python program to sort a list of tuples alphabetically

Given a list of tuples, write a Python program to sort the tuples alphabetically by the first item of each tuple. Examples: Input: [("Amana", 28), ("Zenat", 30), ("Abhishek", 29), ("Nikhil", 21), ("B", "C")] Output: [('Amana', 28), ('Abhishek', 29), ('B', 'C'), ('Nikhil', 21), ('Zenat', 30)] Input: [("aaaa", 28), ("aa", 30), ("bab", 29), ("bb", 21)

3 min read How To Sort List Of Strings In Alphabetically

When working with Python programs, be it any machine learning program or simple text processing program, you might have come across a need to sort a list of strings alphabetically, either in ascending or reverse order. Strings are sorted alphabetically based on their initial letter (a-z or A-Z). But, the strings that start with uppercase characters

3 min read Python Program that Displays the Letters that are in the First String but not in the Second

Python program to display the letters in the first string but not in the second can be done by taking two sets and subtracting them. As sets support the difference operator, one set could contain the letters of the first string and another set could contain the letters of the second string and when subtracted we could obtain the desired result. Exa

5 min read How to Remove Letters From a String in Python

Strings are data types used to represent text/characters. In this article, we present different methods for the problem of removing the ith character from a string and talk about possible solutions that can be employed in achieving them using Python. Input: 'Geeks123For123Geeks'Output: GeeksForGeeksExplanation: In This, we have removed the '123' ch

6 min read Python | Insert value after each k letters in given list of string

Given a list of string, write a Python program to Insert some letter after each k letters in given list of strings. As we know inserting element in a list is quite common, but sometimes we need to operate on list of strings by considering each letter and insert some repeated elements some fixed frequency. Let's see how to achieve this task using Py

5 min read Python | First N letters string construction

Sometimes, rather than initializing the empty string, we need to initialize a string in a different way, vis., we may need to initialize a string with 1st N characters in English alphabets. This can have applications in competitive Programming. Let's discuss certain ways in which this task can be performed. Method #1: Using join() + list comprehens

4 min read Python program to verify that a string only contains letters, numbers, underscores and dashes

Given a string, we have to find whether the string contains any letters, numbers, underscores, and dashes or not. It is usually used for verifying username and password validity. For example, the user has a string for the username of a person and the user doesn't want the username to have any special characters such as @, $, etc. Prerequisite: Regu

4 min read Python program to check if lowercase letters exist in a string

Given a string, the task is to write a Python program to check if the string has lowercase letters or not. Examples: Input: "Live life to the fullest" Output: true Input: "LIVE LIFE TO THe FULLEST" Output: true Input: "LIVE LIFE TO THE FULLEST" Output: false Methods 1#: Using islower() It Returns true if all cased characters in the string are lower

5 min read Python program to calculate the number of digits and letters in a string

Given a string, containing digits and letters, the task is to write a Python program to calculate the number of digits and letters in a string. Example:Input: string = "geeks2for3geeks" Output: total digits = 2 and total letters = 13 Input: string = "python1234" Output: total digits = 4 and total letters = 6 Input: string = "co2mpu1te10rs" Output:

7 min read Python | Ways to split a string in different ways

The most common problem we have encountered in Python is splitting a string by a delimiter, But in some cases we have to split in different ways to get the answer. In this article, we will get substrings obtained by splitting string in different ways. Examples: Input : Paras_Jain_Moengage_best Output : ['Paras', 'Paras_Jain', 'Paras_Jain_Moengage',

2 min read Regex in Python to put spaces between words starting with capital letters

Given an array of characters, which is basically a sentence. However, there is no space between different words and the first letter of every word is in uppercase. You need to print this sentence after the following amendments: Put a single space between these words. Convert the uppercase letters to lowercase Examples: Input : BruceWayneIsBatmanOut

2 min read Python | Remove all characters except letters and numbers

Given a string, the task is to remove all the characters except numbers and alphabets. String manipulation is a very important task in a day to day coding and web development. Most of the requests and responses in HTTP queries are in the form of Python strings with sometimes some useless data which we need to remove. Remove all characters except le

4 min read Python Program that Displays Letters that are not common in two strings

Given two strings. write a Python program to find which letters are in the two strings but not in both. Example: Input: india australia Output: s t r n d u l Steps to be performed: Take two string inputs and store them in different variables.Convert them into a set and look for letters inside in two strings but not in both.Store those letters in a

3 min read Get the Outer Product of an array with vector of letters using NumPy in Python

In this article let's see how to get the outer product of an array with a vector of letters in Python. numpy.outer() method The numpy.outer() method is used to get the outer product of an array with a vector of elements in Python. A matrix is the outer product of two coordinate vectors in linear algebra. The outer product of two vectors with dimens

4 min read Python regex to find sequences of one upper case letter followed by lower case letters

Write a Python Program to find sequences of one upper case letter followed by lower case letters. If found, print 'Yes', otherwise 'No'. Examples: Input : GeeksOutput : YesInput : geeksforgeeksOutput : NoPython regex to find sequences of one upper case letter followed by lower case lettersUsing re.search() To check if the sequence of one upper case

2 min read MoviePy – Text with moving Letters

In this article we will see how we can move the letters of the text clip MoviePy. MoviePy is a Python module for video editing, which can be used for basic operations on videos and GIF’s. Video is formed by the frames, combination of frames creates a video each frame is an individual image. VideoClip is the base class for all the other video clips

4 min read Ways to sort list of dictionaries by values in Python - Using lambda function

In this article, we will cover how to sort a dictionary by value in Python. Sorting has always been a useful utility in day-to-day programming. Dictionary in Python is widely used in many applications ranging from competitive domain to developer domain(e.g. handling JSON data). Having the knowledge to sort dictionaries according to their values can

2 min read Python | Ways to sort a zipped list by values

Zipped lists are those lists where several lists are mapped together to form one list which can be used as one entity altogether. In Python Zip() function is used to map different lists. Let's discuss a few methods to demonstrate the problem. Method #1: Using lambda and sort C/C++ Code # Python code to demonstrate # sort zipped list by values # usi

2 min read Python | Ways to sort list of float values

Given a list of float values, write a Python program to sort the list. Examples: Input: list = ['1.2', '.8', '19.8', '2.7', '99.8', '80.7'] Output: ['.8', '1.2', '2.7', '19.8', '80.7', '99.8'] Input: list = [12.8, .178, 1.8, 782.7, 99.8, 8.7] Output: [0.178, 1.8, 8.7, 12.8, 99.8, 782.7] Let's discuss different ways to solve this problem. Method #1

4 min read Python | Ways to sort list of strings in case-insensitive manner

Given a list of strings, A task is to sort the strings in a case-insensitive manner. Given below are a few methods to solve the task. Method #1: Using casefold() C/C++ Code # Python code to demonstrate to sort list of # strings in case insensitive manner # Initialising list ini_list = ['akshat', 'garg', 'GeeksForGeeks', 'Alind', 'SIngh', 'manjeet',

4 min read Ways to sort list of dictionaries by values in Python – Using itemgetter

In this article, we will cover how to sort a dictionary by value in Python. To sort a list of dictionaries by the value of the specific key in Python we will use the following method in this article. In everyday programming, sorting has always been a helpful tool. Python's dictionary is frequently utilized in a variety of applications, from those i

2 min read Python Program for Odd-Even Sort / Brick Sort

This is basically a variation of bubble-sort. This algorithm is divided into two phases- Odd and Even Phase. The algorithm runs until the array elements are sorted and in each iteration two phases occurs- Odd and Even Phases. In the odd phase, we perform a bubble sort on odd indexed elements and in the even phase, we perform a bubble sort on even i

2 min read Sort a list in Python without sort Function

Python Lists are a type of data structure that is mutable in nature. This means that we can modify the elements in the list. We can sort a list in Python using the inbuilt list sort() function. But in this article, we will learn how we can sort a list in a particular order without using the list sort() method. Sort a List Without Using Sort Functio

3 min read Sort a Dictionary Without Using Sort Function in Python

As we all know Dictionaries in Python are unordered by default, which means they can’t be sorted directly. However, we can sort the keys or values of a dictionary and create a new sorted dictionary from the sorted keys or values. We can sort a list in a Dictionary using the inbuilt dictionary sort() function. But in this article, we will learn how

3 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 : Using list comprehension + sorted() + join() This is

4 min read Add elements in start to sort the array | Variation of Stalin Sort

Stalin sort (also 'dictator sort' and 'trump sort') is a nonsensical 'sorting' algorithm in which each element that is not in the correct order is simply eliminated from the list. This sorting algorithm is a less destructive variation of Stalin sort, that will actually sort the list: In this case, the elements that are not in order are moved to the

6 min read Sort an array using Bubble Sort without using loops

Given an array arr[] consisting of N integers, the task is to sort the given array by using Bubble Sort without using loops. Examples: Input: arr[] = <1, 3, 4, 2, 5>Output: 1 2 3 4 5 Input: arr[] = <1, 3, 4, 2>Output: 1 2 3 4 Approach: The idea to implement Bubble Sort without using loops is based on the following observations: The sorting algorith

9 min read Find length of a string in python (6 ways)

Strings in Python are immutable sequences of Unicode code points. Given a string, we need to find its length. Examples: Input : 'abc' Output : 3 Input : 'hello world !' Output : 13 Input : ' h e l l o ' Output :14 Methods#1: Using the built-in function len. The built-in function len returns the number of items in a container. C/C++ Code # Python co

3 min read Article Tags :