How to check if characters in a string are alphabetically ordered

后端 未结 5 531
面向向阳花
面向向阳花 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条回答
  •  猫巷女王i
    2021-01-26 08:41

    You could see this answer and use something which works for any sequence:

    all(s1[i] <= s1[i+1] for i in xrange(len(s1) - 1))
    

    Example:

    >>> def alp(s1):
    ...     return all(s1[i] <= s1[i+1] for i in xrange(len(s1) - 1))
    ...
    >>> alp("test")
    False
    >>> alp("abcd")
    True
    

自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题