Check if Characters of a 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: 2021-01-15T06:34:35+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements