这是我的密码:
#Printing the original list (This was given)
a = ['spam','eggs',100,1234]
a[0:2] = [1,12]
print("This is the original list:", a)
#Prompting user to input data
b = input('Please add your first item to the list: ')
c = input('Please add your second item: ')
a[4:4] = b
a[5:5] = c
#Printing new list
print(a)
当我运行它并将项目添加到列表中时,它会打印那里的每个字符,所以hello会变成'h'、'e'、'l'、'l'、'o'甚至数字都会这样做,你能帮我解决这个问题吗?你知道吗
因为当您向列表中添加字符串时,它们将成为列表中的单个字符:
如果要将字符串添加到列表末尾,请使用
append
:或者将
string
包装成list
或使用list.insert
:注意:仅在Python2.7上测试
赋值运算符要求在右边有一个iterable
a[4:4] = b
因此,当您
input
一个字符串时,它将它视为一个iterable,并将iterable的每个值赋给列表。 如果需要使用相同的代码,请使用[string]
作为输入。否则使用列表方法,如append
相关问题 更多 >
编程相关推荐