python - 无法将多个字符串添加到列表中

标签 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'对象没有属性'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/

相关文章:

python - 使用 pd.merge 从另一个数据帧映射数据帧中多列的值

python - 你如何将字符串转换为python中的函数?

python - 使用一个输入参数在python中序列化一棵二叉树

python - PyTorch DataLoader 将批处理作为列表返回,并将批处理作为唯一条目。从我的 DataLoader 获取张量的最佳方法是什么

python - 在所有数据帧列上应用不同 bin 大小的 binning

c++ - 无法在 python 中加载 C++ DLL

python - 为什么在使用 Python 2.7.11 IDLE 时无法保存中文文件?

javascript - Python3 执行 Javascript

python - 与 MATLAB 的 imgaussfilt 相比,为什么使用 skimage 和 scipy 的二维高斯滤波之间的速度差异如此之大?

javascript - 使用 JavaScript 将 var res 更改为给定数组的最大值