![](/img/trans.png)
[英]In Python: How do I print the elements as a string from a text file the same way as it appears in the file?
[英]How can I print elements from an imported text file in Python?
好的,所以我的作业被告知要导入一个txt文件并将其存储在列表中,我已经正确地做到了,下一步是将项目打印在3x3网格中。 我想出了一个解决方案,但是它似乎无法正常工作。这是我的代码:
import time
import random
words = open("Words.txt","r")
WordList = []
for lines in words:
WordList.append(lines)
WordList=[line.rstrip('\n')for line in WordList]
print(WordList(0,2))
我的解决方案是从列表中一次打印3个,所以我将打印位置0、1和2。然后我将打印3、4和5,然后我将打印6、7和8,然后有我的解决方案。
我的问题的答案很简单:
print(WordList[0:3])
print(WordList[3:6])
print(WordList[6:9])
尝试将这些行拆分为一个列表,然后在打印列表的同时每打印第三行添加一个新行,不要将这些行附加到WordList中。
words= words.rstrip('\n')
WordList = words.split(" ")
count = 0
for word in WordList:
if count % 3 == 0:
print("\n")
print (word)
count++
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.