Pls how do I solve this 🙏 | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Pls how do I solve this 🙏

In the "Book titles" project. They asked to print the first letter and the length of the title. i.e "Harry Potter" prints "H12" My code: file = open("books.txt", "r" ) for book in file length = str(len(book)) start = book[0] print (start + length) My Output: H13 T17 P20 G18 Their Output: H12 T16 P19 G18

13th Jun 2021, 12:20 PM
Nwalozie Elijah
Nwalozie Elijah - avatar
5 Answers
+ 4
Elijah Nwalozie , a very short version would be: for line in open("/usercode/files/books.txt", "r"): print(f'{line[0]}{len(line.strip())}')
14th Jun 2021, 8:36 PM
Lothar
Lothar - avatar
+ 4
Elijah Nwalozie , to get rid of the problem having a "\n" (newline) at some lines when reading from the file, you could use a string method that will strip away all kinds of whitespace from the string. as a newline sequence is also a whitespace, you can use this procedure: ... ... some_string.strip()): ...
13th Jun 2021, 2:22 PM
Lothar
Lothar - avatar
+ 3
Also, remember that all lines, except the last one, contain a \n at the end, which should not be included in the character count.
13th Jun 2021, 12:22 PM
JaScript
JaScript - avatar
+ 1
Oh thanks
13th Jun 2021, 12:23 PM
Nwalozie Elijah
Nwalozie Elijah - avatar
+ 1
Thanks Lothar. I never knew the use of the strip() method. file = open("/usercode/files/books.txt", "r") i = 1 name = file.readlines() #your code goes here for book in name: if i < len(name): print(book[0] + str(len(book) - 1)) i += 1 else: print(book[0] + str(len(book))) file.close() This was the code I later used. Anyone know a shorter way I can write this?
14th Jun 2021, 7:14 AM
Nwalozie Elijah
Nwalozie Elijah - avatar