Python program to sort strings by substring range

Sorting strings by substring range allows you to order a list based on specific character positions within each string. Python provides an efficient way to achieve this using the sort() method with a custom key function.

Basic Example

Here's how to sort strings based on characters at positions 1 to 3 ?

def get_substring(my_string):
    return my_string[1:3]

words = ["python", "is", "fun", "to", "learn"]

print("Original list:")
print(words)

print("\nSubstring range: positions 1-3")
print("Substrings used for sorting:")
for word in words:
    print(f"'{word}' ? '{word[1:3]}'")

words.sort(key=get_substring)

print("\nSorted result:")
print(words)
Original list:
['python', 'is', 'fun', 'to', 'learn']

Substring range: positions 1-3
Substrings used for sorting:
'python' ? 'yt'
'is' ? 's'
'fun' ? 'un'
'to' ? 'o'
'learn' ? 'ea'

Sorted result:
['learn', 'to', 'is', 'fun', 'python']

Using Lambda Function

You can achieve the same result using a lambda function for more concise code ?

words = ["python", "is", "fun", "to", "learn"]

# Sort using lambda function
words.sort(key=lambda x: x[1:3])

print("Sorted using lambda:")
print(words)
Sorted using lambda:
['learn', 'to', 'is', 'fun', 'python']

Flexible Substring Range

Create a more flexible function that accepts different start and end positions ?

def sort_by_substring(string_list, start, end):
    """Sort strings by substring from start to end position"""
    return sorted(string_list, key=lambda x: x[start:end])

words = ["programming", "coding", "python", "java", "script"]

print("Original list:")
print(words)

# Sort by characters at positions 0-2
result1 = sort_by_substring(words, 0, 2)
print(f"\nSorted by positions 0-2:")
print(result1)

# Sort by characters at positions 2-4  
result2 = sort_by_substring(words, 2, 4)
print(f"\nSorted by positions 2-4:")
print(result2)
Original list:
['programming', 'coding', 'python', 'java', 'script']

Sorted by positions 0-2:
['coding', 'java', 'programming', 'python', 'script']

Sorted by positions 2-4:
['coding', 'java', 'programming', 'script', 'python']

How It Works

The sorting process works as follows:

  • The sort() method uses the key parameter to determine sorting criteria

  • The key function extracts a substring from each string using slice notation [start:end]

  • Python compares these substrings alphabetically to determine the final order

  • Strings with lexicographically smaller substrings appear first in the sorted result

Conclusion

Sorting strings by substring range is useful for organizing data based on specific character patterns. Use the key parameter with sort() and substring slicing to achieve flexible sorting based on any character range within your strings.

Updated on: 2026-03-26T01:13:17+05:30

535 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements