![](/img/trans.png)
[英]Program that reads a vote text file and prints the outcome not printing the right numbers
[英]how to create a program that reads the data from the text file and prints it out in two different sections
我需要一個程序將文件中的“姓名”和“生日”分組,然后將它們打印成兩個不同的部分,如下所示:
姓名 A Masinga 等 出生日期 1988 年 7 月 21 日等
名字應該只是名字的第一個字母,然后顯示姓氏。
這是我的代碼:
name = []
birthdate = []
#open the file
f = open("DOB.txt", "r+")
for line in f:
parts = line.split()
name.append(parts[:2])
birthdate.append(parts[2:])
print("Name")
for i, name in enumerate(name):
print("{}.{}".format(i," ".join(name)))
print("Birthdate")
for i, birthdate in enumerate(birthdate):
print("{}.{}".format(i," ".join(birthdate)))
假設您的名字和姓氏之間有一個空格,您可以對名為names
的名稱列表執行此操作:
for i, name in enumerate(names):
s_idx = name.find(' ')
print(f'{i} - {name[0]}. {name[s_idx+1:]}')
其中,對於名為'Leon Johnson'
的第一個元素,將是 output:
0 - L. Johnson
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.