簡體   English   中英

Python正在打印每個字符?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM