因为它是作为创建我的目录工作不正常["'carrots, 'tomatoes', 'lettuce'"]
,而不是['carrots, 'tomatoes', 'lettuce']
我有一个文本文件,'carrots, 'tomatoes', 'lettuce'
写在一个行,这是我正在写它变成我的列表:
veggie_list =[]
x = open('veggies.txt','r')
for item in x:
veggie_list.append(item)
试试这个(假设你已经在你的文本文件中多行):
veggie_list = []
with open('veg.txt','r') as x:
for item in x:
veggie_list.extend(item.replace("'", "").split(','))
print(veggie_list)
输出:
['carrots', ' tomatoes', ' lettuce']
如果你只关心你的文本文件的第一行:
veggie_list = []
with open('veg.txt','r') as x:
veggie_list = x.read().replace("'","").split(',')
print(veggie_list)
在Python一个班轮使用列表理解:
with open('veg.txt','r') as x:
print([j for i in x for j in i.replace("'","").split(',')])
解释(用于第一码):
首先,您需要从您已经阅读行(去掉单引号"'carrots', 'tomatoes', 'lettuce'"
从文件)。您可以使用替换()方法str
的对象。此方法返回修改后的字符串的副本,它不会改变原始字符串。
在这之后,你应该留下海峡"carrots, tomatoes, lettuce"
。现在,我已经使用分裂()方法来整串入使用单独的字符串分割","
为分隔符。
该方法返回一个列表['carrots', ' tomatoes', ' lettuce']
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句