- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
Advertisements