Python 列表(表)列表中的打印字符串
我对python非常业余,目前我正在打开文件,阅读并打印内容。基本上,我希望将文件中的内容打印到包含以下内容的表中:Python 列表(表)列表中的打印字符串,python,list,Python,List,我对python非常业余,目前我正在打开文件,阅读并打印内容。基本上,我希望将文件中的内容打印到包含以下内容的表中: South Africa:France Spain:Chile Italy:Serbia 以下是我的代码: fileName = input("Enter file name:") openFile = open(fileName) table = [] for contents in openFile: ListPrint = contents.split()
South Africa:France
Spain:Chile
Italy:Serbia
以下是我的代码:
fileName = input("Enter file name:")
openFile = open(fileName)
table = []
for contents in openFile:
ListPrint = contents.split()
table.append(ListPrint)
print(table)
这样做之后,我得到了我想要的东西,它是以表格的形式出现的,在表格中,它由列表的列表组成。然而,我关心的是字符串“南非”,它在这里打印成这样:
['South','Africa:France']
是否有任何方法可供我编写python代码以提供:
['South Africa:France']
非常感谢您的帮助。使用分隔符
contents.split(“:”)
首先,取消该列表/列表想法列表。你想要一本字典。
其次,您要按空格分割字符串,但需要按:字符分割
>>> with open('file.txt') as f:
... countries = {}
... for line in f:
... first, second = line.strip().split(':')
... countries[first] = second
...
>>> countries
{'Italy': 'Serbia', 'Spain': 'Chile', 'South Africa': 'France'}
>>> countries['South Africa']
'France'
如果你要把东西组合在一起,我建议你使用字典。但根据文件内容的外观,很难告诉您如何处理它。如果每一行是一对,它们之间用:分隔,我会用它作为分隔符来拆分。