0
Help!!!
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
8 Respostas
+ 3
file = open("/usercode/files/books.txt", "r")
lines=file.read().splitlines()
for line in lines:
c=str(len(line))
print(line[0]+c)
file.close()
+ 2
John it doesn't work
+ 1
I have a problem with solving codes with files
+ 1
Wijdene Madiouni
Readlines method keeps "\n" as part of the line, hence the length is +1.
One could use .strip() to avoid this, but the task asks to count the spaces (not sure about the trailing ones, though, but better safe, than sorry).
I decided to go with plain checking, whether the "\n" char is in the line (the last line of the file might not have one). Since backslash cannot be included in the f-string, "\n" is substituted with its ascii number, so сhr(10) == "\n".
The updated code:
https://code.sololearn.com/c8CdWlB0GhtK/?ref=app
0
Just means you have to open the file with the provided file name and assign it to a variable. Then do some type of read(e.g. readline(), readlines()) method on that object.
0
Wijdene Madiouni
Open the file, read all the lines.
Iterate over the read lines and produce the string in the desired formatting - first char, len of the string.
Join will join all the produced strings with "\n", which is the newline character, so we'll have all the formatted strings on their own lines.
https://code.sololearn.com/c8CdWlB0GhtK/?ref=app
0
https://code.sololearn.com/c4A2385A0A4A/?ref=app
0
with open('books.txt') as f:
# remove leading and trailing newline characters from each title
titles = list(map(lambda x: x.strip(), f.readlines()))
for title in titles:
print(title[0], len(title), sep='')