Python正在打印每一个角色?

时间:2014-11-16 17:30:40

标签: python string python-3.x

这是我的代码:

#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'即使数字这样做,你能不能帮我解决这个问题?

2 个答案:

答案 0 :(得分:2)

因为当您将列表添加到列表中时,它们将成为列表中的单个字符:

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']

答案 1 :(得分:0)

note :仅在python 2.7上测试

当你执行

时,赋值运算符期望右边的迭代

a[4:4] = b

所以当你input一个字符串时,它会将它视为一个可迭代的,并将iterable的每个值分配给列表。 如果您需要使用相同的代码,请使用[string]作为输入。否则使用列表方法,如append

Please add your first item to the list: ['srj']
Please add your second item: [2]
[1, 12, 100, 1234, 'srj', 2]