Reputation: 5
I’m working on exercises in Python, I'm a beginner. I have a problem with this exercise:
Book Titles
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.
I understand what I should do but my output is not the same as (S9 or A12)..
This is my code…
file = open("/usercode/files/books.txt", "r")
for i in file.readlines():
print(i[0])
print(len(i))
file.close()
my output is:
H
13
T
17
P
20
G
18
Expected Output
H12
T16
P19
G18
Upvotes: 0
Views: 771
Reputation: 155363
You missed the part of the instructions where it says "remember that all lines, except the last one, contain a \n
at the end, which should not be included in the character count."
I'd suggest stripping off the newline, e.g. print(len(i.strip('\n')))
.
To get them all on the same line, just combine the prints, and use an empty sep
:
for i in file:
i = i.strip('\n')
print(i[0], len(i), sep='')
Upvotes: 1