2017-02-04 21 views
-4

我有一個List,x = [「apple」,「banana」,「carrot」,「cheese」,「pear」],我會寫在一行代碼中執行時會返回「蘋果香蕉胡蘿蔔芝士和梨子」。如何在字符串列表中刪除逗號,寫入一行代碼

非常感謝您的幫助!

+2

到目前爲止您嘗試了什麼?檢查'str.join()'函數:https://docs.python.org/2/library/stdtypes.html#str.join – yedpodtrzitko

+0

當我在我的IDLE控制檯中寫入x.join()時:AttributeError:'列表'對象沒有屬性'加入' – iratxe

+1

@Wander Nauta,謝謝你是我搜索! 。我有谷歌搜索,我還沒有finde這個答案....所以,感謝您的鏈接。 – iratxe

回答

-1

最佳答案來自Yousaf。

X = [ 「蘋果」, 「香蕉」, 「胡蘿蔔」, 「乾酪」, 「梨」]

打印( 「\」「+ 'S'。加入(X [ - 1] )+「s」+「and」+(x [4])+「s」+「\」「)

-1

您需要使用加入,就像辛說

arr = ["apple", "banana", "carrot", "cheese", "pear"] 
my_string = " ".join(arr) 

那麼你也可以這樣做:

arr = ["apple", "banana", "carrot", "cheese", "pear"] 
my_string = "" 
for (n in range(len(arr)): 
    if n > 0: 
    my_str += " " + arr[n] 
    else: 
    my_str += arr[n] 

只是爲了讓我的回答看起來比其他人不同。

相關問題