+ 1

Optimize code

Hi, I did and passed the book titles quiz within Python Core with this code below but I feel there should be a cleaner or more nicer way to solve it. Each line of the txt file contains a movie and I need to get the initial and the length of the movie. if you can find a nicer way. Perhaphs I shoud use readline()? thanks: file = open("/usercode/files/books.txt", "r") #your code goes here line=list(file) l=0 for w in line: if (w.find("\n")>0): l=len(w)-1 print(w[0]+str(l)) else: l=len(w) print(w[0]+str(l)) file.close()

10th Jan 2023, 9:47 AM
Ruben
Ruben - avatar
9 Answers
+ 9
Ruben, Mirielle, when iterating over a file object (textIOwrapper) we dont need to call readlines(). see following sample. this code has an improved readability: with open('/usercode/files/books.txt', 'r') as file: res = [f'{n[0]}{len(n.rstrip())}' for n in file] print(*res,sep='\n') an other approach is: for item in open('/usercode/files/books.txt', 'r').read().split('\n'): print(item[0], len(item), sep='') since there is no explicitly difinition of a file object in this last sample, we can not explicitly close this file. i suppose this is done automatically after iteration is done or when the program is getting terminated. https://code.sololearn.com/c34lASo3Xfa3/?ref=app
10th Jan 2023, 3:45 PM
Lothar
Lothar - avatar
+ 3
You mean in any other way: You can use replace method as w = w.replace ("\n", "") No need if part then.
10th Jan 2023, 10:03 AM
Jayakrishna 🇼🇳
+ 3
Another's way you can use strip() method. w = w.strip() also : w[-1] == "\n" instead of find() You're welcome..
10th Jan 2023, 10:18 AM
Jayakrishna 🇼🇳
+ 2
Thanks again, yes, this strip() method is helpful too
10th Jan 2023, 10:23 AM
Ruben
Ruben - avatar
+ 1
Sorry, I meant books instead of movies. I struggled with the last line of the txt file since it did not contain a new line character...
10th Jan 2023, 9:58 AM
Ruben
Ruben - avatar
+ 1
Thanks a lot Mirielle, so helpful, you really optimized it indeed
10th Jan 2023, 10:38 AM
Ruben
Ruben - avatar
+ 1
Thanks a lot Lothar! Very helpful
10th Jan 2023, 6:21 PM
Ruben
Ruben - avatar
0
Thanks Jayakrishna, very helpful! I dont need the if part anymore using the replace()
10th Jan 2023, 10:07 AM
Ruben
Ruben - avatar