删除字符串python2.7中的单个字符

2024-09-29 23:32:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经写了上面的程序。如果str中有chr,并且字符follow chr与chr不同,程序应该从str中删除chr。在

有谁能帮我一下这是怎么回事?为什么工作不正常?我看到函数内部的函数调用有一些问题。在

def removesingleton(str,chr):
    '''
    (str,str)->(str)
    Returns str with removed single chr 
    >>>removesingleton("Welcomee","e")
    Wlcomee
    >>>removesingleton("XabXXaX","X")
    abXXa
    '''
    output, index = "", 0
    if str:
        for char in str:
            if char == chr:
                if index+1 < len(str) and str[index+1] == chr:
                    output += str[:index+2]
                    removesingleton(str[index+2:],chr)
                else:
                    removesingleton(str[index+1:],chr)
            else:
                output += str[index]
                removesingleton(str[index+1:],chr)   
            index += 1
    return output

print removesingleton("XabXXaX","X")

Tags: 函数程序outputindexifdef字符else
1条回答
网友
1楼 · 发布于 2024-09-29 23:32:20

你不需要任何递归调用。它们是完全不必要的,因为您在单个调用中对整个字符串执行循环。(您还忽略了返回值,因此递归一开始没有多大意义。)

您需要检查下一个字符和前一个字符,看看当前字符是否是重复序列的一部分。您不需要执行任何切片,甚至不需要显式循环。下面是代码的工作版本,在str.join调用中被提炼为一个生成器表达式:

def removesingleton(s, ch):
    '''
    (str,str)->(str)
    Returns a copy of s with all non-repeated instances of ch removed 
    >>>removesingleton("Welcomee","e")
    Wlcomee
    >>>removesingleton("XabXXaX","X")
    abXXa
    '''
    return "".join(c for i, c in enumerate(s)     # enumerate gives us our index
                   if c != ch or          # keep any of:  non-matching characters
                      (i > 0 and s[i-1] == ch) or       # previous character was the same
                      (i < len(s)-1 and s[i+1] == ch))  # next character is the same

相关问题 更多 >

    热门问题