简体   繁体   中英

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:

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? 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

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'. 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 .

import re

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

Or just str.replace .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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