简体   繁体   English

如何不将字符串转换为列表?

[英]How to not convert string into a list?

I am making an item menu in console app whereby i get the data from a text file and print it as shown in the code snippet below.我正在控制台应用程序中制作一个项目菜单,我从文本文件中获取数据并打印它,如下面的代码片段所示。

 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")

My problem here is that, in my data there are names like "Full_Cream_Milk" which will be joined together with a "_" so i am using.split() to try to remove it and change print it as "Full Cream Milk", but in doing so it will change my itemName variables into a list which causes the error:我的问题是,在我的数据中有像“Full_Cream_Milk”这样的名称,它将与“_”连接在一起,所以我正在使用.split() 尝试将其删除并将其更改为“Full Cream Milk”,但这样做会将我的 itemName 变量更改为导致错误的列表:

Exception has occurred: TypeError
can only concatenate str (not "list") to str

my question now is that, how do i not make my itemName into a list?我现在的问题是,我如何不将我的 itemName 放入列表中? Or are there any better ways to remove the "_"?或者有没有更好的方法来删除“_”?

I have also tried writing it as shown below and it still changes it into string and I'm not sure is it because im getting the data from a list or what because it worked before adding the split() function我也尝试过如下所示编写它,它仍然将其更改为字符串,我不确定是因为我从列表中获取数据还是因为它在添加 split() function 之前有效

itemName = everything[1]
itemName = itemName.split("_")

My guess is you want to split 'Full_Cream_Milk' by '_' and later join the split part as 'FullCreamMilk'.我的猜测是您想将“Full_Cream_Milk”拆分为“_”,然后将拆分部分作为“FullCreamMilk”加入。 In that case, the following snippet will do the work.在这种情况下,以下代码段将完成这项工作。

itemName = everything[1]
split_words = itemName.split("_")
itemName = ''.join(split_words)

If you wish to remove all of the underscores, you can use re.sub .如果你想删除所有的下划线,你可以使用re.sub

import re

itemName = re.sub('_', '', everything[1])

Or just str.replace .或者只是str.replace

itemName = everything[1].replace('_', '')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM