so I making an app that prints the first letter and the no of words including space in each element in a list in python in the same line
so the list is a file which with the help of readlines() I have converted into a variable that can be used as a list this is my code that can print the first letter of each element in that list so now I just have to print the no of letters in each element in the list I will provide my code, current output, expected output, and the file
file = open("/usercode/files/books.txt", "r")
#your code goes here
contentlines = file.readlines()
content = file.read()
no_of_words = str(len(contentlines[0]))
for first_letter in contentlines:
print(first_letter[0])
file.close()
current output
H
T
P
G
expected output
H12
T33
P18
D16
the file content
Harry Potter
The Red and the Black by Stendhal
Pride and Prejudice
David Copperfield
With a little bit of modification on your own code:
file = open("books.txt", "r")
#your code goes here
contentlines = file.readlines()
content = file.read()
for line in contentlines:
if line[-1] != "\n":
no_of_words = len(line)-1
else:
no_of_words = len(line)
print(line[0], no_of_words, sep="")
file.close()
H12
T33
P19
D17
Note that, in the len(line)-1
, the -1
refers to the break line shown by "\n". It is counted as one character:
myname = "\n"
print(len(myname))
This will output
1