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
CodePudding user response:
IIUC, you can simplify your code to loop and print at the same time:
with open('/usercode/files/books.txt', 'r') as f:
for line in f:
L = len(line.rstrip('\n'))
print(f'{line[0]}{L}')
output:
H12
T33
P19
D17
CodePudding user response:
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:
no_of_words = len(line)-1
print(line[0], no_of_words, sep="")
file.close()
Output
H12
T33
P19
D16
Note that, in the len(line)-1
, the -1
refers to the break line shown by "\n". It is counted as one character.