not getting expected output >> H12 T16 P19 G18 | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

not getting expected output >> H12 T16 P19 G18

You have been asked to make a special book categorization program, which assigns each book a special code based on its title. The code is equal to the first letter of the book, followed by the number of characters in the title. For example, for the book "Harry Potter", the code would be: H12, as it contains 12 characters (including the space). You are provided a books.txt file, which includes the book titles, each one written on a separate line. Read the title one by one and output the code for each book on a separate line. For example, if the books.txt file contains: Some book Another book Your program should output: S9 A12 https://code.sololearn.com/cR8EIkeKR3KB/?ref=app https://code.sololearn.com/cR8EIkeKR3KB/?ref=app

11th Jun 2021, 10:18 AM
Likhon
Likhon - avatar
7 Answers
+ 2
Likhon Zamader , what you need to do is: ▪︎read each line from the file (already done!) ▪︎take each line in the for loop and do: ▪︎take the first character of this string (you can access it by its index) ▪︎take the string and get the length of it (there is a build-in function that can do that) ▪︎take the first letter and concatenate the length of the string to a new string (remember that the length is currently an integer, that has to be converted) ▪︎print out the new string inside the for loop happy coding and good success!
11th Jun 2021, 10:35 AM
Lothar
Lothar - avatar
+ 4
what output do you expect? your code prints out each line in the file exactly how its coded. Try using previous lesson knowledge to deal with the strings
11th Jun 2021, 10:20 AM
Slick
Slick - avatar
+ 1
Thanks
11th Jun 2021, 10:37 AM
Likhon
Likhon - avatar
+ 1
Loathar , Why need this line : line = line.replace('\n' , ' ') if I don't write this line the output is: H13 T17 P20 G18 Correct output: H12 T16 P19 G18 Why increases by 1 if I don't write that line
11th Jun 2021, 2:06 PM
Likhon
Likhon - avatar
+ 1
because if you readline() from the file, the new line ending each of them (except the last one) is counted in string length ^^ alternatively, you could read the whole file at once and split("\n") the string: iterating over the array would return you each line without the ending "\n" ;)
11th Jun 2021, 3:56 PM
visph
visph - avatar
+ 1
file = open("/usercode/files/books.txt", "r") lines=file.readlines() for line in lines: print(line[0]+str(len(line)-1)) # As it count \n element too.so to ignore it we have reduce the length by 1. file.close()
13th Jun 2021, 8:40 AM
Abhinandan Prasad
- 1
6th May 2022, 9:35 AM
ELENA