我开始制作一个程序,您可以在其中添加列表并搜索它。一切都很顺利,直到错误不断出现。
_list = []
def variables(variable):
return variable.title()
while True:
inputt = input("\nPrint c to create/add to a program\nand s to search for"
" something that is in that list, enter 'q' when u ready")
if inputt == 'c':
while True:
create_something = input("What is the item you want to add your list")
_list.append(create_something)
_list = str(_list)
print("This is your list so far\n" + _list)
if create_something == 'q':
print("This is yo' list so far")
break
elif input == 's':
print("cool")
当我尝试向列表中添加多个项目时,它显示'str'对象没有属性'append'
。
最佳答案
append 仅适用于列表,不适用于字符串。如果您想转换为字符串以仅打印,请考虑仅使用 str(_list)
进行打印或使用 join
方法。
这是一个使用 join 的示例:
_list = []
def variables(variable):
return variable.title()
while True:
inputt = input("\nPrint c to create/add to a program\nand s to search for something that is in that list, enter 'q' when u ready")
if inputt == 'c':
while True:
create_something = input("What is the item you want to add your list")
_list.append(create_something)
print("This is your list so far\n" + ''.join(_list))
if create_something == 'q':
print("This is yo' list so far")
break
elif input == 's':
print("cool")
将 _list
保留为列表,但是在打印它们时 - 使用 join 将它们打印为字符串。
Print c to create/add to a program
and s to search for something that is in that list, enter 'q' when u ready'c'
What is the item you want to add your list'foo'
This is your list so far
foo
What is the item you want to add your list' bar'
This is your list so far
foo bar
What is the item you want to add your list' baz'
This is your list so far
foo bar baz
关于python - 无法将多个字符串添加到列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53136461/