Check if a given word contains consecutive letters in Python using Functions

In this Python tutorial, we shall check whether a given word contains a sequence of two consecutive letters or not using ASCII values.

What do we mean?

If a given word has a substring like ‘ab’, ‘rs’, ‘hi’ or something similar, then we say that it has consecutive letters since b comes after a, s comes after r, i comes after h and so on.

  1. The word ‘Abbot’ has the letters ‘a’ and ‘b’ in succession. Hence it is a word that has a sequence of two consecutive letters.
  2. The word ‘Alone’ does not have any succession of letters that are consecutive in nature.

Let us look at the Python code and the output that we get!

Python program: Check if a given word contains consecutive letters

Code in Python:-

#Function to check for consequtive letters in the word
def isConseq(word):
    word = word.upper()
    for i in range(0,len(word)-1):
        if (ord(word[i]) + 1) == ord(word[i+1]):
            return True
    return False
    
list = ['Abbot', 'Alone', 'Abstract', 'String', 'Education', 'Python']
for w in list:
    if(isConseq(w)):
        print(f"'{w}' contains consequtive letters")
    else:
        print(print(f"'{w}' does not contain consequtive letters"))

Output:-

'Abbot' contains consequtive letters
'Alone' does not contain consequtive letters
None
'Abstract' contains consequtive letters
'String' contains consequtive letters
'Education' does not contain consequtive letters
None
'Python' does not contain consequtive letters

Let us now look at the explanation of the Python Code!

Explanation of the Python Code

–> isConseq() function:-

  • The word where the criteria check occurs is taken as the argument.
  • Convert all the characters of the word to its upper case because when we check for consecutive letters using ASCII values, we want all the characters in the same case.
  • Run a loop from index 0 to len(word)-1, which is the upper bound of the index of the string.
  • Convert the character at the index equivalent to the loop counter to its equivalent ASCII value using the ord() method in Python.
  • Check if the ASCII value is 1 less than the ASCII value of the character at the index equivalent to the loop counter + 1.
  • If the condition specified in the above point is satisfied then the function returns True, else the function returns False.

Also read: Taking a number and rearranging its digits in ascending order to form a new number in Python

Leave a Reply

Your email address will not be published. Required fields are marked *