才學沒幾天,學到串列了,在做練習的時候碰到了這個問題,沒有把第四行搞明白,為什么fruit[6:]是str型別?
(第一張是報錯提示,第二張是添加了str函式后的結果,第三張是練習題)
(文本問題代碼為:
fruit = ['orange', 'watermelon', 'pineapple', 'banana', 'apple', 'mango', 'grapefruit', 'pomegranate', 'winter date']
print('The first three items in the list are:' + str(fruit[:3]))
print('The items from the middle of the list are:' + str(fruit[3:6]))
print('The last three items in the list are:' + fruit[6:]))


uj5u.com熱心網友回復:
1、因為你print里邊使用了“+”(加號),這里使用加號意思為字串拼接;2、你看你前兩個列印,都進行了強制轉換,前邊加了str;
3、使用“+”(加號)進行字串拼接的話,“+”(加號)前后必須型別一致,都為str型別。
4、比如你使用:
print(fruit[6:])
可以看到結果為
['grapefruit', 'pomegranate', 'winter date']
這是一個串列,而不是字串,所以你要在前邊加str進行強制轉換:
print('The last three items in the list are:' + str(fruit[6:]))結果為:
The last three items in the list are:['grapefruit', 'pomegranate', 'winter date']
uj5u.com熱心網友回復:
再補充一下,如果你不想進行強制型別轉換,那你直接輸入你需要列印的值即可,不適用“+”(加號)進行字串拼接,把“+”(加號)進行改為“,”(逗號)就行了。如下:print('The last three items in the list are:', fruit[6:])結果為:
The last three items in the list are: ['grapefruit', 'pomegranate', 'winter date']
和你要的結果是一樣的
uj5u.com熱心網友回復:
多謝大佬


轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/244889.html
