Python – Extract Strings with Successive Alphabets in Alphabetical Order

When working with strings, you may need to extract strings that contain successive alphabets in alphabetical order. This means finding strings where at least two consecutive characters follow each other in the alphabet (like 'hi' where 'h' and 'i' are consecutive).

Understanding Successive Alphabets

Successive alphabets are characters that follow each other in the alphabet sequence. For example:

  • 'ab' - 'a' and 'b' are successive

  • 'hi' - 'h' and 'i' are successive

  • 'xyz' - 'x', 'y', 'z' are all successive

Method: Using ord() Function

The ord() function returns the Unicode code point of a character. For consecutive alphabets, their Unicode values differ by exactly 1.

Example

my_list = ["python", 'is', 'cool', 'hi', 'Will', 'How']

print("The list is:")
print(my_list)

my_result = []

for element in my_list:
    for index in range(len(element) - 1):
        if ord(element[index]) == ord(element[index + 1]) - 1:
            my_result.append(element)
            break

print("The result is:")
print(my_result)
The list is:
['python', 'is', 'cool', 'hi', 'Will', 'How']
The result is:
['hi']

How It Works

The algorithm works by:

  • Iterating through each string in the list

  • For each string, comparing consecutive characters using their Unicode values

  • If ord(char1) == ord(char2) - 1, the characters are successive

  • Adding the string to results and breaking to avoid duplicates

Example with More Successive Alphabets

test_strings = ["abc", "xyz", "hello", "world", "def", "random"]

result = []

for string in test_strings:
    for i in range(len(string) - 1):
        if ord(string[i]) == ord(string[i + 1]) - 1:
            result.append(string)
            break

print("Strings with successive alphabets:")
print(result)
Strings with successive alphabets:
['abc', 'xyz', 'def']

Key Points

  • The ord() function converts characters to their Unicode values

  • Successive alphabets have Unicode values that differ by 1

  • The break statement prevents adding the same string multiple times

  • This method works for both lowercase and uppercase letters

Conclusion

Use the ord() function to compare Unicode values of consecutive characters. This method efficiently identifies strings containing successive alphabets by checking if character values differ by exactly 1.

Updated on: 2026-03-26T01:10:56+05:30

246 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements