无法在列表中添加多个字符串

时间:2018-11-03 23:34:43

标签: python

我开始制作一个程序,您可以在其中添加列表,然后搜索整个列表。一切都很好,直到错误不断出现。

_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' object has no attribute 'append'

2 个答案:

答案 0 :(得分:1)

append仅适用于列表,不适用于字符串。如果要将转换为字符串以仅打印,则可以考虑仅将Group 2用于打印或使用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") 保留为列表,但是在打印它们时-使用join将它们打印为字符串。

_list

答案 1 :(得分:0)

此行将random.choice转换为字符串,并且不再是列表:

lists = [['B', '13', 'ß'],
         ['o', 'ø', 'Ö'],
         ['A', 'Ä', 'Á']]
word = ''
for lst in lists:
    word += random.choice(lst)
print(word)

因此,当您的循环第二次执行时,它将尝试运行_list并抛出您报告的错误。