【发布时间】: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。但是你不会对结果做任何事情。你不应该把它分配到某个地方吗? -
你不应该使用
str和chr作为变量名——它们会影响内置函数 -
@Kevin 我实际上使用它们将切片字符串发送到函数。所以我将添加我已经添加到输出的字符。我看到函数调用存在问题。但我自己想不通。
-
运行这个会发生什么?在代码中添加日志语句以观察某些更改的值通常是我做过的最有用的调试。
标签: python string function python-2.7