0
Book titles
How do i complete that practice called book titles, and i am stuck at that part to print first char and num of chars including spaces
16 Réponses
+ 4
Post the code you have tried.
You have to:
- open the file
- give it a name
- use readlines() to make a list of titles
- print the first letter of each title and its length
- for all the titles except the last one, shorten the length by 1 so as not to count the "\n" at the end.
- close the file
+ 4
A simpler way with 5 lines of code.
A simple explanation, loop through all lines, and if a line has trailing/ending "\n" remove it from the count of the length.
https://code.sololearn.com/cdaPdMWWeN3W/?ref=app
+ 3
probably by using title(). But the only way anyone can help for sure is by posting your code, with a description of where you're stuck
JFMINEBOY João Felipe post your code so we can see where the problem might be
+ 2
So far so good. Now that you have a list of the titles, loop through it and print the first character and length of each title.
+ 2
I finished the task but I wonder why \n counts as one character instead of two ("\" and "n")
+ 2
Rami Muleys line[] is cyclic. line[0] is the first character. If you have 10 characters, line[9] is the last character.
Due to cyclic, line[-1] is the also last character. And this is more dynamic and it works all for numbers of character length.
+ 1
How using readlines? I am trying titles = file.readlines()
+ 1
But i get invalid syntax on a line that do not exists?!
+ 1
JFMINEBOY João Felipe I suspect you may have copied and pasted a nonprinting character. I suggest starting over with a new code and type it in from scratch.
+ 1
thank you Lam
0
- open the file
- give it a name
- use readlines() to make a list of titles
- print the first letter of each title and its length
- for all the titles except the last one, shorten the length by 1 so as not to count the "\n" at the end.
- close the file
file = open("/usercode/files/books.txt", "r")
#your code goes here
lines = file.readlines()
for line in lines:
letter = line[0]
if line[-1] == "\n":
number = len(line)-1
else:
number = len(line)
print (str(letter) + str(number))
file.close()
0
\n here is a new line tag so it is counted as one
0
ould you please explain why line[-1] is considered as the end of the string?
0
I am beyond confused how solo learn expects us to know all of this from the stuff they teach us.
- 2
#Here is the code
file=open("/usercode/files/books.txt", "r")
p=file.readlines()
for i in p:
letter=i[0]
if i[-1]=="\n":
number=len(i)-1
else:
number=len(i)
print(str(letter)+str(number))
file.close()