所以我的程序要求用户在文本文件中输入他们想要的任何内容(我把它命名为chapter14file.txt)。一旦完成,他们应该进入“完成”。所以我创建了一些打印语句来确保一切正常。如果我运行这个程序并转到有问题的print语句(最后一行),它将显示比我输入的更多的内容。如果我在单独的行中输入:
1个
二
试验
三
完成
现在我完了。所以我输入“done”,它进入print语句并显示: ['1','2','Test','3','']
因此,重要的是要知道我的任务是将用户输入转换为列表。这就是为什么项目在方括号中
chapter14file = open ("chapter14file.txt", "w+")
while True:
user_item = str (input ("Please enter what you would like to be added to chapter14file.txt. Type 'done' when you are finished. ") )
if user_item.upper() == "DONE":
break
else:
chapter14file.write (user_item + ",")
chapter14file.close()
items_from_file = (open ("chapter14file.txt").read())
items_list = items_from_file.split(",")
items_list_capital = [ elem.upper() for elem in items_list ] #Converts each element of the list to only have capital letters, no lowercase letters. Makes the search case insensitive.
print (items_from_file, items_list, items_list_capital)
应输入(与前面的示例保持一致):['1','2','Test','3']
实际值:['1','2','Test','3','']
注意:当我谈论结果时,“具体来说,在两个小撇号之间什么都没有
这就是问题所在:
您将
,
附加到每个条目。最后一个条目看起来像:当您获取这个字符串并在
,
处拆分它时,由于最后一个,
字符,您将得到一个空字符串您可以通过删除最后一个
,
或剥离空字符串来修复它对于“,”也可以保持相同的格式,但对于while语句,请尝试以下操作: y=0; 如果为真: 用户\u item=str(输入(“请输入您想要添加到chapter14file.txt的内容。完成后键入“done”。)
使用变量y来查找第一个值
相关问题 更多 >
编程相关推荐