AttributeError: 'list' object has no attribute 'replace' out = [j.replace("on", "re") for j in out]
AttributeError: 'list' object has no attribute 'replace' out = [j.replace("on", "re") for j in out]
我正在尝试用用户词替换这些词。这两个词都取自用户。但是我不知道这是怎么回事。
def practiseeight():
number = str(request.args.get('num'))
on = str(request.args.get('one'))
re = str(request.args.get('two'))
value = number.split('<')
print(value)
out = []
for i in value:
i = i.split('>')
out.append(i)
print("This is",out)
out = [j.replace("on", "re") for j in out]
print("new list", out)
您的代码中的问题:
out = []
for i in value:
i = i.split('>') # so you are splitting i, split return a list
out.append(i) # you are appending i which is a list
print("This is",out)
out = [j.replace("on", "re") for j in out] # now you are going through each element in out, each element is a list. List do not have replace, strings do!
要在列表列表中替换:
out = [['abc'], ['abc', 'bcd']]
for i in out: # go through each element in out
for j,v in enumerate(i): i[j] = v.replace('b','e') # go through each element in the list of list and replace
print(out)
[['aec'], ['aec', 'ecd']]
正如其他答案正确提到的那样,您的变量 'out' 变成了一个列表列表,因为您将 'i' (这是一个列表)附加到变量 'out' 中。请尝试使用 'out.extend'。
out = []
for i in value:
i = i.split('>')
out.extend(i) ## this will add the element 'i' to the end of the existing list 'out'
print("This is",out)
out = [j.replace("on", "re") for j in out]
print("new list", out)
我正在尝试用用户词替换这些词。这两个词都取自用户。但是我不知道这是怎么回事。
def practiseeight():
number = str(request.args.get('num'))
on = str(request.args.get('one'))
re = str(request.args.get('two'))
value = number.split('<')
print(value)
out = []
for i in value:
i = i.split('>')
out.append(i)
print("This is",out)
out = [j.replace("on", "re") for j in out]
print("new list", out)
您的代码中的问题:
out = []
for i in value:
i = i.split('>') # so you are splitting i, split return a list
out.append(i) # you are appending i which is a list
print("This is",out)
out = [j.replace("on", "re") for j in out] # now you are going through each element in out, each element is a list. List do not have replace, strings do!
要在列表列表中替换:
out = [['abc'], ['abc', 'bcd']]
for i in out: # go through each element in out
for j,v in enumerate(i): i[j] = v.replace('b','e') # go through each element in the list of list and replace
print(out)
[['aec'], ['aec', 'ecd']]
正如其他答案正确提到的那样,您的变量 'out' 变成了一个列表列表,因为您将 'i' (这是一个列表)附加到变量 'out' 中。请尝试使用 'out.extend'。
out = []
for i in value:
i = i.split('>')
out.extend(i) ## this will add the element 'i' to the end of the existing list 'out'
print("This is",out)
out = [j.replace("on", "re") for j in out]
print("new list", out)