我创建了一些混乱的字符串并试图修复它。最终我遇到了我的功能不起作用但手动输入的相同代码有效的问题。问题: 为什么在 Python 中相同的代码在函数中不起作用,但是当您手动编写相同的代码时它确实起作用?这是代码: #A variable x = "apples and oranges!" #Making a variable messed up strings x = "-".join(x) x = str(x.split("-")) #Creating automatic function for cleaning messed up strings def clnStr(x): y = x y = y.replace("'", "") y = y.replace(",", "") y = y.replace("[", "") y = y.replace("]", "") y = y.replace(",", "") y = y.replace(" ", "") clnStr(x) print(x) #Cleaning up string variable manually y = x y = y.replace("'", "") y = y.replace(",", "") y = y.replace("[", "") y = y.replace("]", "") y = y.replace(",", "") y = y.replace(" ", "") print(y)# Repairing string variablefor i, index in enumerate(y): #Getting a list of indexes of a string variable print(i, index)y = y[0:6] + " " + y[6:9] + " " + y[9:]print(y)#cannot repair 'x' variable with same method because the function does not work as it should.
1 回答

莫回无
TA贡献1865条经验 获得超7个赞
你没有从你的clnStr函数中返回任何东西。尝试:
def clnStr(x):
y = x
y = y.replace("'", "")
y = y.replace(",", "")
y = y.replace("[", "")
y = y.replace("]", "")
y = y.replace(",", "")
y = y.replace(" ", "")
return y
z = clnStr(x)
print(z)
添加回答
举报
0/150
提交
取消