【问题标题】:Remove Single Char in String Python 2.7删除字符串 Python 2.7 中的单个字符
【发布时间】:2014-07-30 00:42:47
【问题描述】:

我已经编写了上面的程序。如果 str 中有 chr 并且字符跟随 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")

【问题讨论】:

  • 我看到你在 removesingleton 内部打电话给 removesingleton。但是你不会对结果做任何事情。你不应该把它分配到某个地方吗?
  • 你不应该使用 strchr 作为变量名——它们会影响内置函数
  • @Kevin 我实际上使用它们将切片字符串发送到函数。所以我将添加我已经添加到输出的字符。我看到函数调用存在问题。但我自己想不通。
  • 运行这个会发生什么?在代码中添加日志语句以观察某些更改的值通常是我做过的最有用的调试。

标签: python string function python-2.7


【解决方案1】:

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

您需要检查下一个字符和前一个字符,以查看当前字符是否是重复序列的一部分。您不需要进行任何切片,甚至不需要显式循环。这是代码的工作版本,在 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

【讨论】:

    猜你喜欢
    • 2017-03-27
    • 2017-05-17
    • 2013-02-01
    • 2023-04-09
    • 1970-01-01
    • 2022-12-20
    • 1970-01-01
    • 2023-02-16
    • 1970-01-01
    相关资源
    最近更新 更多