[英]How to not convert string into a list?
我正在控制台應用程序中制作一個項目菜單,我從文本文件中獲取數據並打印它,如下面的代碼片段所示。
with open("itemList.txt", "r") as itemFile:
for row in itemFile:
row = row.strip("\n")
itemlist.append(row.split())
print("\n---------------------")
print("Welcome!"+userName)
print("---------------------\n")
for everything in itemlist:
itemCode = everything[0]
itemName = str(everything[1]).split("_")
itemPrice = everything[2]
itemQuantity = everything[3]
print(itemCode+"\t|"+itemName+"\t|"+itemPrice+"\t|"+itemQuantity+"\n")
我的問題是,在我的數據中有像“Full_Cream_Milk”這樣的名稱,它將與“_”連接在一起,所以我正在使用.split() 嘗試將其刪除並將其更改為“Full Cream Milk”,但這樣做會將我的 itemName 變量更改為導致錯誤的列表:
Exception has occurred: TypeError
can only concatenate str (not "list") to str
我現在的問題是,我如何不將我的 itemName 放入列表中? 或者有沒有更好的方法來刪除“_”?
我也嘗試過如下所示編寫它,它仍然將其更改為字符串,我不確定是因為我從列表中獲取數據還是因為它在添加 split() function 之前有效
itemName = everything[1]
itemName = itemName.split("_")
我的猜測是您想將“Full_Cream_Milk”拆分為“_”,然后將拆分部分作為“FullCreamMilk”加入。 在這種情況下,以下代碼段將完成這項工作。
itemName = everything[1]
split_words = itemName.split("_")
itemName = ''.join(split_words)
如果你想刪除所有的下划線,你可以使用re.sub
。
import re
itemName = re.sub('_', '', everything[1])
或者只是str.replace
。
itemName = everything[1].replace('_', '')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.