
- 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 strings by substring range
When it is required to sort the strings based on a substring range, a method us defined that uses list slicing to determine the result.
Example
Below is a demonstration of the same −
def get_substring(my_string): return my_string[i : j] my_list = ["python", 'is', 'fun', 'to', 'learn'] print("The list is :") print(my_list) i, j = 1, 3 print("The value of i and j are :") print(str(i)+ ',' +str(j)) my_list.sort(key=get_substring) print("The result is :") print(my_list)
Output
The list is : ['python', 'is', 'fun', 'to', 'learn'] The value of i and j are : 1,3 The result is : ['learn', 'to', 'is', 'fun', 'python']
Explanation
A method named ‘get_substring’ is defined that takes a string as a parameter.
It uses list slicing to get values within given range.
Outside the method, a list of strings is defined and is displayed on the console.
The values for two variables are defined and displayed on the console.
The list is sorted based the key as the previously defined method.
This list is displayed on the console as the output.
- Related Articles
- Python program to Sort Strings by Punctuation count
- Python – Sort by range inclusion
- Python – Sort Strings by Case difference
- Python program to Sort a List of Strings by the Number of Unique Characters
- Python – Sort by Rear Character in Strings List
- Python program – All occurrences of Substring from the list of strings
- Program to check whether string Is transformable with substring sort operations in Python
- Java Program to set a range for displaying substring
- Python Program to Join strings by multiple delimiters
- Python Program to Sort a Tuple By Values
- Python – Filter Strings within ASCII range
- Python – Sort given list of strings by numeric part of string
- Python Program to compare two strings by ignoring case
- Python How to sort a list of strings
- Python program to Sort Tuples by their Maximum element

Advertisements