假设每个名字只是一个名字和姓氏,没有中间名等等,你可以简单地读取文件的每一行,并根据空格进行拆分。下面将捕获first to fields in first and last,然后捕获dob中的其余字段。然后我们就可以用变量打印这两行。不需要在文件数据中循环两次。
with open('test.txt') as my_file:
for person in my_file:
first, last, *dob = person.rstrip().split()
print(f"Name: {first[0]}. {last}")
print(f"Birthdate: {' '.join(dob)}")
Name: O. Wright
Birthdate: 21 July 1988
Name: R. Holloway
Birthdate: 13 September 1988
Name: M. Figueroa
Birthdate: 9 October 1988