PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, September 16, 2022

[FIXED] how to print the no of letters including space in each element in list in python

 September 16, 2022     element, letter, list, printing, python     No comments   

Issue

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

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


Answered By - TheFaultInOurStars
Answer Checked By - Mary Flores (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing