+ 1
Please solve the following question
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 ответов
+ 5
Amidu Yohan
the issue with this exercise is, that the lines we have to read from the file have ALL (!!! except the last one !!!) a trailing new-line sequence (\n).
so using some arithmetic operations to handle this, will not give a correct result.
the pythonic way of solving this task is to use the string method .rstrip(), which will remove all white-space characters at the end of a string. since new-line sequences are also considered as white-space characters, this way will work.
this your code slightly fixed:
file = open("/usercode/files/books.txt", "r")
while True:
t = file.readline()
L = list(t)
if len(t) == 0:
break
else:
print(f"{L[0]}{(len(t.rstrip()))}") # used f-string to create the output string // used t.rstrip() to remove new-line sequences
file.close()
+ 1
print(L[0]+str(len(t)-1))
+ 1
https://code.sololearn.com/cnR5VYOKlV4s/?ref=app
0
file = open("/usercode/files/books.txt", "r")
#your code goes here
while True:
t = file.readline()
L = list(t)
if len(t) == 0:
break
else:
print(L[0],(len(t)-1))
file.close()
0
Can anyone tell whether my phython code is true? Jay Matthews
0
file = open("/usercode/files/books.txt", "r")
for line in file.readlines():
print("\n" + line[0] + str(len(line)))
file.close
0
Loveit=("Comments")
print (Loveit)
print ("I \nlove \nProgramming\n!")
print ("Share\nand\ndrink\nLatte")
print ("Vaccinated")
print ("Please get the vaccine as fast as you can")
negative=("negative")
print ("Fast test "+negative)
PunchBag=(" ")
print ("Punch Bag"+PunchBag)
print ("Bye Bye") ?