
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Python program to sort string in custom order
Suppose we have one alphanumeric string s. We have to sort it based on following condition
All sorted lowercase letters will be placed before uppercase letters.
All sorted uppercase letters will be placed before digits.
All sorted odd digits will be placed before sorted even digits.
So, if the input is like s = "HeLlo1234", then the output will be eloHL1324
To solve this, we will follow these steps −
- Define a function f() . This will take c
- code := 0
- if c is in upper case, then
- code := 10^3
- otherwise when c is a digit, then
- code := 10^6
- if ASCII of c is even, then
- code := 10^9
- return code + ASCII of c
- From the main method do the following
- l := sorted list of s and order each character c in s by calling f() function
- join each character in l and return
Example
Let us see the following implementation to get better understanding
def f(c): code = 0 if c.isupper(): code = 10 ** 3 elif c.isdigit(): code = 10 ** 6 if ord(c) % 2 == 0: code = 10 ** 9 return code + ord(c) def solve(s): l = sorted(s, key=lambda c: f(c)) return ''.join(l) s = "HeLlo1234" print(solve(s))
Input
"HeLlo1234"
Output
eloHL1324
- Related Articles
- Implement Custom Sort Order in MySQL
- Custom Sort String in C++
- C program to sort names in alphabetical order with string functions.
- Python Program to sort a tuple of custom objects by properties
- Python Program to Split a String by Custom Lengths
- Python program to sort tuples in increasing order by any key.
- Program to merge intervals and sort them in ascending order in Python
- Python Program to sort rows of a matrix by custom element count
- C++ Program to Sort Elements in Lexicographical Order (Dictionary Order)
- Java Program to Sort Elements in Lexicographical Order (Dictionary Order)
- Swift Program to Sort Elements in Lexicographical Order (Dictionary Order)
- Kotlin Program to Sort Elements in Lexicographical Order (Dictionary Order)
- Haskell Program to Sort Elements in Lexicographical Order (Dictionary Order)
- Python program to sort out words of the sentence in ascending order
- Program to sort a given linked list into ascending order in python

Advertisements