[英]Python is printing every character?
这是我的代码:
#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)
当我运行它并将其添加到列表中时,它会在其中打印每个字符,因此问候变为'h','e','l','l','o'即使是数字,您也可以帮我解决这个?
因为当您向这样的列表中添加字符串时,它们会成为列表内的单个字符:
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]
如果要将字符串添加到列表的末尾,请使用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']
或将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']
注意 :仅在python 2.7上测试
赋值运算符在您执行操作时会期望在右侧进行迭代
a[4:4] = b
因此,当您input
字符串时,会将其视为可迭代的字符串,并将可迭代的每个值分配给列表。 如果需要使用相同的代码,请使用[string]
作为输入。 否则使用列表方法,例如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.