+ 2

Can anyone help with tho SoloLearn project

I'm trying to print the first letter of a line and it's length in front of it but I'm printing it with a space does anyone know how to fix that: file = open("/usercode/files/books.txt", "r") for line in (file): print(line[0],len(line)-1) file.close()

18th Mar 2022, 11:36 AM
Gonçalo Vicente
6 Réponses
+ 4
Gonçalo Vicente , the space you are talking about is coming from the print statement, where the arguments to print are separated by a comma. this inserts a space between the arguments. an other issue is, that by reading from the file, the lines (except the last one) additionally contains a *new-line sequence*. with using ...-1 in the print statement, you try to *correct* this issue, but for the last line it is not suitable. instead of using ...-1 we can use the strip() method, that removes all trailing and leading *white spaces* and also the *new-line sequences* so finally the line in the code is: ... print(line[0],len(line.strip()),sep="") [Edited] ...
18th Mar 2022, 12:03 PM
Lothar
Lothar - avatar
+ 3
If you convert the number to a string there will be no space: print(line[0] + str(len(line.strip())))
18th Mar 2022, 9:31 PM
Brian
Brian - avatar
+ 2
line.strip()
18th Mar 2022, 11:39 AM
Slick
Slick - avatar
+ 2
Thanks
18th Mar 2022, 12:06 PM
Gonçalo Vicente
+ 2
It can be formatted so that there is no blank space: print("%s%s" % (line[0],len(line)-1))
18th Mar 2022, 8:46 PM
Monica Garcia
Monica Garcia - avatar
+ 1
You can fix it for example with a rpleace statement as follows: … line.replace(" ","") …
18th Mar 2022, 11:43 AM
JaScript
JaScript - avatar