我正在嘗試從列表中加入單詞并將其轉換為字符串我嘗試過 .join 方法,但由于我的列表中只有一項,所以它不起作用。我的輸入 = list = ['Vehicles, Parts & Accessories,Automotive Body Paint']期望的輸出 =str = Vehicles-Parts-&-Accessories-Automotive-Body-Paint
3 回答

aluckdog
TA貢獻1847條經驗 獲得超7個贊
首先,您的列表只有一項,因此請通過 訪問它my_str = my_lst[0]
。然后刪除,
并替換為-
:
my_str = my_str.replace(',','').replace(' ', '-')
輸出:
'Vehicles-Parts-&-AccessoriesAutomotive-Body-Paint'

侃侃無極
TA貢獻2051條經驗 獲得超10個贊
您可以使用正則表達式來執行此操作,讓我們找到所有重復的單詞字符組,或者&將它們與-. 解決方案適用于多個字符串的列表。
import re
l = ['Vehicles, Parts & Accessories,Automotive Body Paint']
['-'.join(re.findall('[\w&]+', words)) for words in l]
輸出
['Vehicles-Parts-&-Accessories-Automotive-Body-Paint']

郎朗坤
TA貢獻1921條經驗 獲得超9個贊
這可以滿足您的需求:
lst = ['Vehicles, Parts & Accessories,Automotive Body Paint']
string = lst[0].replace(',',' ').replace(' ','-')
輸出:
'Vehicles--Parts-&-Accessories-Automotive-Body-Paint'
注意:盡量不要使用strorlist作為變量名,因為 Python 保留那些供內部使用,你會以這種方式禁用它們。
添加回答
舉報
0/150
提交
取消