'please explain to me how i could better code this out

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

Recall the readlines() method, which returns a list containing the lines of the file.
Also, remember that all lines, except the last one, contain a \n at the end, which should not be included in the character count.


This is a website I'm using to learn python and I am stuck because i don't know where to use readlines() and I don't really know why I need to use it. (It has to be used.) My code below shows me printing every name in the file and only getting its first letter. My mistake is when I run this code I get the same exact thing I wanted except my last digit is off because of spaces.

#given code
file = open("/usercode/files/books.txt", "r")

#my code

for name in file:
    
    print(name[0] + str(len(name)-1))

file.close()

OUTPUT:

Your Output
H12
T16
P19
G17
Expected Output
H12
T16
P19
G18


Solution 1:[1]

The instructions say:

Also, remember that all lines, except the last one, contain a \n at the end

You're subtracting 1 from the length of all lines, including the last one.

Instead of subtracting 1 from the length and special-casing the last line, you can use the rstrip() method to remove a newline at the end of the string.

for name in file.readlines():
    print(name[0] + str(len(name.rstrip('\n'))))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1