line[0] prints the first letter of A line. But I Also Require Len of that element. Eg. B5 for BOOKS. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

line[0] prints the first letter of A line. But I Also Require Len of that element. Eg. B5 for BOOKS.

file = open("/usercode/files/books.txt", "r") for line in file: print(line[0]+file.write("/usercode/files/books.txt"))#This don't works, don't Concatenate

16th Feb 2021, 5:31 AM
We Doru
We Doru - avatar
14 Answers
+ 1
check my updated answer (to convert length to string): I forgotten the str() call ^^
16th Feb 2021, 5:50 AM
visph
visph - avatar
+ 1
you probably should check your closing parenthesis ^^
16th Feb 2021, 5:57 AM
visph
visph - avatar
+ 1
then use: print(line[0]+str(len(line)-(1 if line[-1]=='\n' else 0))) it will substract 1 if last line char is the new line char ;)
16th Feb 2021, 6:06 AM
visph
visph - avatar
+ 1
you don't want to use file.write(), as you don't want to modify the file ^^ and even by writing in a temporary file, you will get the line length plus one (the new line)... if you want to do so, you need to open a temporary file with 'w' flag instead of 'r'
16th Feb 2021, 6:17 AM
visph
visph - avatar
+ 1
just use the strip() method on the string to remove the '\n' then get its length print(line[0]+str(len(line.strip())))
16th Feb 2021, 6:35 AM
ChaoticDawg
ChaoticDawg - avatar
0
print(line[0]+str(len(line)))
16th Feb 2021, 5:47 AM
visph
visph - avatar
0
visph I tried but it cAnnot concatenate string and numbers eg. In BOOKS, B and 5 is concatenated. But How
16th Feb 2021, 5:49 AM
We Doru
We Doru - avatar
0
It is sAying EOF While Parsing
16th Feb 2021, 5:55 AM
We Doru
We Doru - avatar
0
It is close. EXPECTED Output is H12, T16, P19, G18 But I got H13, T17, P20, G18
16th Feb 2021, 6:03 AM
We Doru
We Doru - avatar
0
Seems like file.write() need to be used to print the length insteAd of length function
16th Feb 2021, 6:05 AM
We Doru
We Doru - avatar
0
file.write() will write into file ^^
16th Feb 2021, 6:08 AM
visph
visph - avatar
0
How do I use readlines and print(file.write()) to Achieve the sAme Above
16th Feb 2021, 6:11 AM
We Doru
We Doru - avatar
0
Seems like need more in-depth AnAlyse. ThAnks much
16th Feb 2021, 6:13 AM
We Doru
We Doru - avatar
0
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
17th Feb 2021, 3:31 AM
Lam Wei Li
Lam Wei Li - avatar