我创建了一些混乱的字符串,并试图对其进行修复。最终,我遇到了这样的问题:我的函数不起作用,但是手动键入的相同代码起作用。
问题: 为什么在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 variable
for 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.
答案 0 :(得分:3)
您没有从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)