0
Most efficient way to do "Book Titles" Python project?
I was doing the "Book Titles" project for Python Core, but I really have no idea how to do it in the most efficient way. Here's what I did: file = open("/usercode/files/books.txt", "r") #your code goes here c = file.readlines() c0 = c[0] c1 = c[1] c2 = c[2] c3 = c[3] print(c0[0] + str(len(c0) -1)) print(c1[0] + str(len(c1)-1)) print(c2[0] + str(len(c2)-1)) print(c3[0] + str(len(c3))) file.close() Can anyone tell me how I could have spent less time doing this project? Thanks.
3 Respuestas
+ 1
1. You can use a context manager (no need to worry about closing the file, it will be handled for you)
with open('filename', 'r') as file:
2. Then use a for loop to loop through the lines of the file. (You don't actually need to use readlines() or read() here, but you can if preferred)
for line in file:
3. Output the first char of the line (line[0]) and then use the strip() method to remove the trailing newline character '\n' from the line before outputting its len(). You can either concatenate the string or use an f-string for the output.
print(f"{line[0]}{len(line.strip())}")
0
ChaoticDawg Some of that wasn’t even discussed… like the strip() method.
0
Okay, so update…
Looking back at the List Operation “in”, it appears I could have combined an “if” statement with this, like so:
file = open("/usercode/files/books.txt", "r")
#your code goes here
for x in file.readlines():
if "\n" in x:
print(x[0] + str(len(x) - 1))
else:
print(x[0] + str(len(x)))
file.close()