'how to create a program that reads the data from the text file and prints it out in two different sections
I need a program that groups "names" and "birthdates" from a file and then prints them into two different sections as follows:
Name A Masinga Etc. Birthdate 21 July 1988 Etc.
The names should only be the first letter of the name and then display the surname.
here is my code:
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)))
Solution 1:[1]
Assuming you have a space between the first name and the surname, you can do this for a list of names called names:
for i, name in enumerate(names):
s_idx = name.find(' ')
print(f'{i} - {name[0]}. {name[s_idx+1:]}')
Which, for the first element named 'Leon Johnson', would output:
0 - L. Johnson
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
