0
Pls how do I solve this 🙏
In the "Book titles" project. They asked to print the first letter and the length of the title. i.e "Harry Potter" prints "H12" My code: file = open("books.txt", "r" ) for book in file length = str(len(book)) start = book[0] print (start + length) My Output: H13 T17 P20 G18 Their Output: H12 T16 P19 G18
5 Respostas
+ 4
Elijah Nwalozie ,
a very short version would be:
for line in open("/usercode/files/books.txt", "r"):
print(f'{line[0]}{len(line.strip())}')
+ 4
Elijah Nwalozie ,
to get rid of the problem having a "\n" (newline) at some lines when reading from the file, you could use a string method that will strip away all kinds of whitespace from the string. as a newline sequence is also a whitespace, you can use this procedure:
...
... some_string.strip()):
...
+ 3
Also, remember that all lines, except the last one, contain a \n at the end, which should not be included in the character count.
+ 1
Oh thanks
+ 1
Thanks Lothar. I never knew the use of the strip() method.
file = open("/usercode/files/books.txt", "r")
i = 1
name = file.readlines()
#your code goes here
for book in name:
if i < len(name):
print(book[0] + str(len(book) - 1))
i += 1
else:
print(book[0] + str(len(book)))
file.close()
This was the code I later used. Anyone know a shorter way I can write this?