0

here is my task:

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
file = open("/usercode/files/books.txt", "r")

with file as f:
    lines = f.readlines()
    for i in lines:
        count = len(i)
        count = str(count - 1)
        print(i[0]+count)
    

file.close()

and this outputs everything correct but the last line because i[#lastLine] is done after the last count if that makes any sense?(could be completely wrong I am learning)

Basically I want to know where I am going wrong in my code. I believe it is the way I structured the for i in lines part and should have handled the \n in a different way to

count = len(i) count = str(count - 1)

ANSWER

Thank you for informing me, adding i = i.strip() strips new lines aka \n which sorted the problem!

Working code:

file = open("/usercode/files/books.txt", "r")

with file as f:
    lines = f.readlines()
    for i in lines:
        i = i.strip('\n') #Strips new lines aka \n
        count = str(len(i))
        print(i[0]+count)
    

file.close()

1 Answers1

0

You can use strip() on i to remove the new lines.

strip - Returns a copy of the string with the leading and trailing characters removed. Python docs strip

you can cast your count as a str() to print.

str() Returns a string containing a printable representation of an object.

Python docs str As comments point out, suggest also changing i to line for readability.

file = open("books.txt", "r")

with file as f:
    lines = f.readlines()
    for line in lines:
        count = str(len(line.strip()))
        print(line[0]+count)
    

file.close()
Josh Adams
  • 2,113
  • 2
  • 13
  • 25