Check if the characters of a given string are in alphabetical order in Python


Suppose we have a string s. We have to check whether characters in s are in alphabetical order or not.

So, if the input is like s = "mnnooop", then the output will be True.

To solve this, we will follow these steps −

  • char_arr := a new list from the characters present in s
  • sort the list char_arr
  • return char_arr is same as list of all characters in s then true otherwise false

Let us see the following implementation to get better understanding −

Example Code

Live Demo

def solve(s):
   char_arr = list(s)
   char_arr.sort()
        
   return char_arr == list(s)
 
s = "mnnooop"
print(solve(s))

Input

"mnnooop"

Output

True

Updated on: 15-Jan-2021

965 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements