Python – Equidistant consecutive characters Strings


When it is required to find equidistant consecutive character strings, a list comprehension, the ‘all’ operator and the ‘ord’ method are used.

Example

Below is a demonstration of the same

my_list = ["abc", "egfg", "mpsv", "abed", 'xzbd', 'agms']

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

my_result = [sub for sub in my_list if all(ord(sub[index + 1]) - ord(sub[index]) == ord(sub[1]) - ord(sub[0]) for index in range(0, len(sub) - 1))]

print("The resultant list is :")
print(my_result)

Output

The list is :
['abc', 'egfg', 'mpsv', 'abed', 'xzbd', 'agms']
The resultant list is :
['abc', 'mpsv', 'agms']

Explanation

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

  • A list comprehension is used to iterate through the list.

  • The ‘all’ operator along with ‘ord’ method is used to check if the difference between next index and current index is equivalent to the first index and zeroth index.

  • This is assigned to a variable.

  • This is displayed as output on the console.

Updated on: 14-Sep-2021

139 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements