Python正在打印每个字符?

2024-04-25 22:05:24 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的密码:

#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'甚至数字都会这样做,你能帮我解决这个问题吗?你知道吗


Tags: thetoadd密码inputyourthisitem
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']

注意:仅在Python2.7上测试

赋值运算符要求在右边有一个iterable

a[4:4] = b

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

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

相关问题 更多 >