0
我寫過上面的程序。如果str中有chr,並且字符跟隨chr,則程序應該從str刪除chr,而不是chr。刪除字符串Python中的單個字符2.7
任何人都可以幫助我這是怎麼回事?爲什麼不按預期工作?我在函數內部看到函數調用的一些問題。
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'。但你對結果沒有做任何事情。你不應該把它分配到某個地方嗎? – Kevin
您不應該使用'str'和'chr'作爲變量名稱 - 它們會影響內置插件 – jonrsharpe
@Kevin我實際上使用它們來發送切片字符串以實現功能。所以我會添加我已經添加的字符輸出。我發現函數調用有問題。但我無法自己弄清楚。 – pythondetective