+ 2
Python Book Titles[SOLVED]
I'm trying figure out the solution for getting the first letter of a book title & length of the title string minus the space at the end. Ex: Input-Harry Potter would output H12 The closest I've got is this code: file = open("/usercode/files/books.txt", "r") while True: t = file.readline() L = list(t) if len(t) == 0 break else: print(L[0],(len(t)-1)) file.close() This is run and the output shows: Input: No input Output: H 12 T 16 P 19 G 17 Expected Output: H12 T16 P19 G18
3 Answers
+ 2
Micah Whitcomb ,
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: (modify only the line that is marked with '<<<')
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
The last line don't have \n character at end so for last it just need is print(L[0]+str(len(t))
Also, Use like this,
print(L[0] + str(len(t)-1) dont put camma in between.
edit:
else use
t = file.readline().strip() # to remove \n
print(L[0]+ str(len(t)))
+ 1
Awesome, thanks for the answers! The first solution worked. Wouldve been nice to learn about the strip() method before doing this exercise!