How can I get the next string, in alphanumeric ordering, in Python?

前端 未结 4 895
走了就别回头了
走了就别回头了 2021-01-05 23:02

I need a simple program that given a string, returns to me the next one in the alphanumeric ordering (or just the alphabetic ordering).

f(\"aaa\")=\"aab\"
f(         


        
4条回答
  •  [愿得一人]
    2021-01-05 23:22

    Sucks that python doesn't have what ruby has: String#next So here's a shitty solution to deal with alpha-numerical strings:

    def next_string(s):
      a1 = range(65, 91)  # capital letters
      a2 = range(97, 123) # letters
      a3 = range(48, 58)  # numbers
      char = ord(s[-1])
      for a in [a1, a2, a3]:
        if char in a:
          if char + 1 in a:
            return s[:-1] + chr(char + 1)
          else:
            ns = next_string(s[:-1]) if s[:-1] else chr(a[0])
            return ns + chr(a[0])
    
    print next_string('abc')  # abd
    print next_string('123')  # 124
    print next_string('ABC')  # ABD
    
    # all together now
    print next_string('a0')   # a1
    print next_string('1a')   # 1b
    print next_string('9A')   # 9B
    
    # with carry-over
    print next_string('9')    # 00
    print next_string('z')    # aa
    print next_string('Z')    # AA
    
    # cascading carry-over
    print next_string('a9')   # b0
    print next_string('0z')   # 1a
    print next_string('Z9')   # AA0
    
    print next_string('199')  # 200
    print next_string('azz')  # baa
    print next_string('Zz9')  # AAa0
    
    print next_string('$a')   # $b
    print next_string('$_')   # None... fix it yourself
    

    Not great. Kinda works for me.

提交回复
热议问题