Python program to check if the characters in a string are sequential

Python program to check if the characters in a string are in sequential order:

In this post, we will learn how to check if the characters in a string are in sequential order. For example, for the string, acdfh, the characters are in sequential order. But, for the string adchf, the characters are not in sequential order.

The python program will take one string as the input. It will check if the characters in the string is in sequential order or not and it will print one message based on that.

Python program:

Below is the complete python program:

def check_sequential(given_str):
    str_length = len(given_str)

    for i in range(1, str_length):
        if ord(given_str[i]) < ord(given_str[i - 1]):
            return False

    return True


given_str = input('Enter a string: ')
if check_sequential(given_str):
    print('The characters are in sequential order')
else:
    print('The characters are not in sequential order')

Here,

  • check_sequential method is used to check if the characters are in sequential order or not.
  • str_length is the length of the string passed to this method as parameter.
  • The for loop runs from index 1 to the end character. For each character, it checks if the ASCII value of the current character is greater than the previous character or not. If not, it returns False.
  • At the end of the method, it is returning True.
  • Based on the check_sequential method, it prints one message.

Sample output:

Let’s take a look at the below output:

Enter a string: abcdegh
The characters are in sequential order

Enter a string: abcedhg
The characters are not in sequential order

python check characters in string sequential

You might also like: