Apr-26-2019, 06:22 PM
So I have a problem that I've been working on for like 8 hours now. It's driving me insane.
The goal here is to open a .txt file I created that contains a list of names that go from top to bottom.
Then I want the program to look at the first letter of each name and see if it is the same as the first letter of the following name.
If the name does not contain the same letter, the program is to use a \n to go to a new line. That way all the first letters are grouped together.
The goal here is to open a .txt file I created that contains a list of names that go from top to bottom.
Then I want the program to look at the first letter of each name and see if it is the same as the first letter of the following name.
If the name does not contain the same letter, the program is to use a \n to go to a new line. That way all the first letters are grouped together.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
def main(): newList = [] #Opens the file. inFile = open ( "names.txt" , 'r' ) #Reads all of the lines and saves them to inRead. inRead = inFile.readlines() #Sorts them alphabetically. inRead.sort() #Performs a loop for how many items are in 'inRead'. for index in range ( len (inRead)): #Strips off all the new lines. inRead[index] = inRead[index].rstrip( '\n' ) #Creats a list called newList. newList = inRead[index] #If the first letter of one name is not the same as the first # letter of the next name then skip a line. if newList[ 0 ][ 0 ] ! = newList[ 0 ][ 1 ]: print ( '\n' ) print (newList) #Closes the file. inFile.close() main() |