+ 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
+ 3
You mean in any other way:
You can use replace method as
w = w.replace ("\n", "")
No need if part then.
+ 3
Another's way you can use strip() method.
w = w.strip()
also : w[-1] == "\n" instead of find()
You're welcome..
+ 2
Thanks again, yes, this strip() method is helpful too
+ 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...
+ 1
Thanks a lot Mirielle, so helpful, you really optimized it indeed
+ 1
Thanks a lot Lothar! Very helpful
0
Thanks Jayakrishna, very helpful! I dont need the if part anymore using the replace()