Reputation: 157
Say I have a text file like that where every new letter starts on a new line:
-.H
-.e
-.l
-.l
-.o
I would like to write a code to remove some data from each text line (in the case of example I would like to remove '-.' in front of each letter) and then concatenate the result back together to form:
Hello
What would be a general approach to this kind of problem? I thought it could be solved in a following way:
f = open('hello.txt', 'r')
logs = f.readlines()
f.close()
loglist = list(map(str.strip, logs))
newlist = []
for i in range (len(loglist)):
splitLetter = loglist[i].split('.')
letter = splitLetter[-1]
newlist.append(letter)
word = ''.join(newlist)
print word
The problem though is that the result is a series of iterations:
H
He
Hel
Hell
Hello
I need only the last result. How do I get that?
Upvotes: 3
Views: 1638
Reputation: 563
Using with ... as
statement frees you from closing the file. It will be automatically closed at the end of the block.
Then, in one single line:
word = ''.join([l.strip()[-1]] for l in logs)
You don't need to split the string if you strip the string before. You can be sure the letter will be at the last index.
Full code:
with open('hello.txt', 'r') as logs:
word = ''.join([l.strip()[-1]] for l in logs)
print word
Upvotes: 0
Reputation: 825
The problem with your current code is that you are printing after every iteration. By moving the print
statement outside of the for-loop it will print only the last iteration.
f = open('hello.txt', 'r')
logs = f.readlines()
f.close()
loglist = list(map(str.strip, logs))
word = ''.join(l.split('.')[-1] for l in loglist)
print word
Just to make sure this works, I tested it out with a test file with the following text:
-.G
-.o
-.o
-.d
-.b
-.y
-.e
and got the following result:
Goodbye
Upvotes: 1
Reputation: 42748
You are printing the result in every step. Simply print after the for loop.
You can use generator expressions for shorter program:
with open('hello.txt') as logs:
word = ''.join(l.strip().split('.')[-1] for l in logs)
print word
Upvotes: 0
Reputation: 12927
word = ''.join([ l.split('.')[-1] for l in loglist ])
instead of the whole for
loop should do.
Upvotes: 0
Reputation: 494
for i in range (len(loglist)):
splitLetter = loglist[i].split('.')
letter = splitLetter[-1]
newlist.append(letter)
word = ''.join(newlist)
print word
or
word = ''
for i in range (len(loglist)):
splitLetter = loglist[i].split('.')
letter = splitLetter[-1]
word += letter
print word
Upvotes: 0
Reputation: 45726
Just move the printing outside of the loop:
for i in range (len(loglist)):
splitLetter = loglist[i].split('.')
letter = splitLetter[-1]
newlist.append(letter)
word = ''.join(newlist)
print word
Upvotes: 0