我创建了一些混乱的字符串并试图修复它。最终我遇到了我的功能不起作用但手动输入的相同代码有效的问题。
问题: 为什么在 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.
莫回无
相关分类