Home > Back-end >  How to stop a new line from being created for each letter in a list after looping?
How to stop a new line from being created for each letter in a list after looping?

Time:02-17

I am trying to figure out how to fix issues regarding new lines being created for every letter in an attempt to display full words of a list in this one Python exercise.

The goal is to convert each word in the resulting list to lowercase and remove all punctuation within the text using a string.

I was able to read a file and split it into a list of individual words using the following code:

file_handle = open('romeo_juliet.txt')
words = file_handle.read()  
words.split()   

Which results in this list output:

['Romeo',
 'and',
 'Juliet',
 'Act',
 '2,',
 'Scene',
 '2',
 'SCENE',
 'II.',
 "Capulet's",
 'orchard.']

I attempted to use this resulting list to lowercase and remove punctuation of individual words and used the following code, with "puncs" being defined as a string of the punctuation to be removed; and using a for loop to split lines, lowercase words, and remove punctuation:

puncs = "-.,?!:;'[]"
def strip_puncs(s):
    return ''.join(c for c in s if c not in puncs)
for hdln in words:
    wot = hdln.split()
    for words_lower in wot:
        words_lower = words_lower.lower()
        words_lower = strip_puncs(words_lower)
        print(words_lower)     

It removes punctuation and lowercases all words, but does not separate individual words and instead creates a new line for every letter as demonstrated in a snippet:

r
o
m
e
o
a
n
d
j
u
l
i
e
t

The goal is to get an output that resembles this:

romeo
and 
juliet

Any help would be appreciated. Thank you in advance.

CodePudding user response:

Your code is working almost fine. You called words.split() but forgot to assign it. the .split() method isn't modifying your string, so you must assign to to then process it, or use it directly in your loop.

This does work :

file_handle = open('test.txt')
words = file_handle.read()  
splitted_words = words.split()
puncs = "-.,?!:;'[]"
def strip_puncs(s):
    return ''.join(c for c in s if c not in puncs)
for hdln in splitted_words :
    wot = hdln.split()
    for words_lower in wot:
        words_lower = words_lower.lower()
        words_lower = strip_puncs(words_lower)
        print(words_lower)  
  • Related