+ 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()
6 Respuestas
+ 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]
...
+ 3
If you convert the number to a string there will be no space:
print(line[0] + str(len(line.strip())))
+ 2
line.strip()
+ 2
Thanks
+ 2
It can be formatted so that there is no blank space:
print("%s%s" % (line[0],len(line)-1))
+ 1
You can fix it for example with a rpleace statement as follows:
… line.replace(" ","") …