# Python program to sort strings by substring range

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

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.

Updated on 08-Sep-2021 07:07:39