[英]Python is printing every character?
This is my code: 这是我的代码:
#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)
When I run it and add items to the list, it prints every character there, so hello becomes 'h','e','l','l','o' Even the numbers do this, could you help me fix this? 当我运行它并将其添加到列表中时,它会在其中打印每个字符,因此问候变为'h','e','l','l','o'即使是数字,您也可以帮我解决这个?
Because when you add strings to a list like that they become individual character inside the list: 因为当您向这样的列表中添加字符串时,它们会成为列表内的单个字符:
In [5]: l = [1,2,3]
In [6]: s = "foo"
In [7]: l[1:1] = s
In [8]: l
Out[8]: [1, 'f', 'o', 'o', 2, 3]
If you want to add the strings to the end of the list use append
: 如果要将字符串添加到列表的末尾,请使用
append
:
In [9]: l = [1,2,3]
In [10]: s = "foo"
In [11]: l.append(s)
In [12]: l
Out[12]: [1, 2, 3, 'foo']
Or wrap the string
in a list
or use list.insert
: 或将
string
包装在list
或使用list.insert
:
In [16]: l[1:1] = [s] # iterates over list not the string
In [17]: l
Out[17]: [1, 'foo', 2, 3, 'foo']
In [18]: l.insert(2,"foo")
In [18]: l
Out[19]: [1, 'foo', 'foo', 2, 3, 'foo']
note : tested only on python 2.7 注意 :仅在python 2.7上测试
the assignment operator expects an iterable in the right-hand side when you do 赋值运算符在您执行操作时会期望在右侧进行迭代
a[4:4] = b
so when you input
a string, it treats it as an iterable and assigns each value of the iterable to the list. 因此,当您
input
字符串时,会将其视为可迭代的字符串,并将可迭代的每个值分配给列表。 if you need to use the same code, use [string]
for the input. 如果需要使用相同的代码,请使用
[string]
作为输入。 else use list methods like append
否则使用列表方法,例如
append
Please add your first item to the list: ['srj']
Please add your second item: [2]
[1, 12, 100, 1234, 'srj', 2]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.