Python 的 Ruby String#succ 对应物?

标签 python

我想知道在 python 中是否有一个函数(或方法)像在 Ruby 的 String#succ 中那样递增字符串方法,即:

~ $ irb --simple-prompt
>> '2'.succ
=> "3"
>> '99'.succ
=> "100"
>> 'zzz'.succ
=> "aaaa"
>>

最佳答案

下面的实现是我能用 String#succ 的 ruby​​ 实现得到的最接近的实现

def succ(s):
    if not isinstance(s, (str,string)):
        raise TypeError("succ works only with strings")
    if not s: return
    if max(map(ord, s)) > 127:
        raise TypeError("succ currently only supports ascii")

    #Three different character category honoured
    #  1. ascii lowercase alpha
    #  2. ascii uppercase alpha
    #  3. digits
    #  4. ascii nonalpha characters (the entire ascii set)
    lower = string.ascii_lowercase + 'a'
    upper = string.ascii_uppercase + 'A'
    digits = string.digits + '0'
    nonalpha = map(chr, range(0, 256)) + [chr(0)]
    def incr(ch):
        '''
        Generates the next character in sequence using the following rules
            1. Incrementing a digit always results in another digit
            2. Incrementing a letter results in another letter of the same case.
            3. Incrementing nonalphanumerics uses the underlying
               character set’s collating sequence.
        '''
        if ch.isdigit(): return digits[ord(ch) - ord("0") + 1]
        if ch.islower(): return lower[ord(ch) - ord('a') + 1]
        if ch.isupper(): return upper[ord(ch) - ord('A') + 1]
        return nonalpha[ord(ch) + 1]
    def last(ch):
        '''
        Returns the last character in its catagory
        '''
        if ch.isdigit(): return digits[-2]
        if ch.islower(): return lower[-2]
        if ch.isupper(): return upper[-2]
        return nonalpha[-2]
    def first(ch):
        '''
        Returns the last first in its catagory
        '''
        if ch.isdigit(): return digits[0]
        if ch.islower(): return lower[0]
        if ch.isupper(): return upper[0]
        return nonalpha[0]
    def islast(ch):
        '''
        Checks if next increment would generate a carry
        '''
        return ch == last(ch)
    s = list(s)[::-1]
    carry = True
    try:
        index = next(i for i, e in enumerate(s) if e.isalnum())
    except StopIteration:
        index = 0
    while carry:

        if index == len(s): #Add a character for Overflow
            s.append(first(s[index - 1]))
            break
        carry =  True if islast(s[index]) else False
        s[index] = incr(s[index])
        index += 1
    return ''.join(s[::-1])

示例用法

succ('2')       - > 3         
succ('99')      - > 000       
succ('zzz')     - > aaaa      
succ('')        - > None      
succ('abcd')    - > abce      
succ('THX1138') - > THX1139   
succ('<<koala>>') - > <<koalb>> 
succ('1999zzz') - > 2000aaa   
succ('ZZZ9999') - > AAAA0000  
succ('***')     - > **+ 

关于Python 的 Ruby String#succ 对应物?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20721214/

相关文章:

python - 使用 aggfunc=sum 的 Pandas Dataframes 值计算在几列上

Python Tkinter,简单示例在 win 7 上失败

python - 对整个句子应用 NLP WordNetLemmatizer 显示错误且位置未知

python - 如何在Python中找到素数

python - PiCamera 将图像存储在 RGBArray 中

python - cd 目录不存在?

python - 以最快的方式查找重复的图像

python - 身份证号码生成器

python - 使用OpenCV时永远弹跳Python Rocket

python - 使用 python 选择特定的 anchor 标签