How to check if characters in a string are alphabetically ordered

后端 未结 5 529
面向向阳花
面向向阳花 2021-01-26 08:18

I have been trying these code but there is something wrong. I simply want to know if the first string is alphabetical.

def alp(s1):
    s2=sorted(s1)
    if s2 i         


        
5条回答
  •  不思量自难忘°
    2021-01-26 08:31

    Make sure that you are comparing strings with strings:

    In [8]: s = 'abcdef'
    
    In [9]: s == ''.join(sorted(s))
    Out[9]: True
    
    In [10]: s2 = 'zxyw'
    
    In [11]: s2 == ''.join(sorted(s2))
    Out[11]: False
    

    If s1 or s2 is a string, sorted will return a list, and you will then be comparing a string to a list. In order to do the comparison you want, using ''.join() will take the list and join all the elements together, essentially creating a string representing the sorted elements.

提交回复
热议问题