Python – Extract Strings with Successive Alphabets in Alphabetical Order


When it is required to extract strings which have successive alphabets in alphabetical order, a simple iteration, and the ‘ord’ method for Unicode representation is used.

Example

Below is a demonstration of the same −

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)

Output

The list is :
['python', 'is', 'cool', 'hi', 'Will', 'How']
The result is :
['hi']

Explanation

  • A list of strings is defined and is displayed on the console.

  • An empty list is defined.

  • The list is iterated over, and the Unicode character of consecutive elements in the list is compared.

  • If they are equal, it is appended to the empty list.

  • The control breaks out of the loop.

  • This list is displayed as the output on the console.

Updated on: 08-Sep-2021

131 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements