My list is not functioning properly because it is created as ["'carrots, 'tomatoes', 'lettuce'"]
rather than ['carrots, 'tomatoes', 'lettuce']
I have a text file with 'carrots, 'tomatoes', 'lettuce'
written on one line, and this is how I am writing it into my list:
veggie_list =[]
x = open('veggies.txt','r')
for item in x:
veggie_list.append(item)
Try this (Assuming you have multiple lines in your text file):
veggie_list = []
with open('veg.txt','r') as x:
for item in x:
veggie_list.extend(item.replace("'", "").split(','))
print(veggie_list)
Outputs:
['carrots', ' tomatoes', ' lettuce']
If you are only interested in the first line of your text file:
veggie_list = []
with open('veg.txt','r') as x:
veggie_list = x.read().replace("'","").split(',')
print(veggie_list)
One Liner in Python using list comprehension:
with open('veg.txt','r') as x:
print([j for i in x for j in i.replace("'","").split(',')])
EXPLANATION (For the first code):
You need to first remove the single quote marks from the line you have read ("'carrots', 'tomatoes', 'lettuce'"
) from the file. You can use replace() method of str
object. This method returns a copy of modified string and it doesn't change the original string.
After that, you should be left with str "carrots, tomatoes, lettuce"
. Now, I have used split() method to divide the whole string into individual strings using ","
as delimiter.
This method returns a list ['carrots', ' tomatoes', ' lettuce']
.