'how to print the no of letters including space in each element in list in python

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


Solution 1:[1]

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()

Output

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

Solution 2:[2]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 mozway