(Python) Question with starts with a repeat statement

Asked 2 years ago, Updated 2 years ago, 14 views

name = input('Enter file name: ')
if len(name) < 1 : name = 'mbox-short.txt'
handle = open(name)

counts = dict()

for line in handle :
    if 'From' in line :
        print(line) 

In the question of finding a specific word, I found it using sentences as usual. That's how it turned out

From [email protected] Sat Jan  5 09:14:16 2008
From: [email protected]
From [email protected] Fri Jan  4 18:10:48 2008
From: [email protected]
From [email protected] Fri Jan  4 16:10:39 2008
From: [email protected]
...

The e-mail address was repeated once again and printed in the same way as above. At that time, I thought it was stored in the text like this. I was searching for the code because I couldn't solve it, so I was searching for the code in the same code

startswith('From')

I only changed it to

From [email protected] Sat Jan  5 09:14:16 2008
From [email protected] Fri Jan  4 18:10:48 2008
From [email protected] Fri Jan  4 16:10:39 2008
From [email protected] Fri Jan  4 15:46:24 2008
From [email protected] Fri Jan  4 15:03:18 2008
From [email protected] Fri Jan  4 14:50:18 2008

As above, the line that had only the email address disappeared. I'm trying to solve it at a different price, so it's a waste. I wonder why the output results are so different in whether or not the function is used. What's the reason? Why was the way I used wrong? Please give me some advice.

python

2022-09-21 22:08

1 Answers

I don't understand the phenomenon of the questioner. You need to know the string in the file to determine the cause.

'From' in line is true if only From exists, and startswith is true if only the string that starts with From is true.

From [email protected] Sat Jan 5 09:14:16 2008 From: [email protected]

If you look at the difference between the two sentences, it looks like a different sentence with a colon (:). Please check if there is a space in front of the sentence and try again by trimming.

L = ('From [email protected] Sat Jan  5 09:14:16 2008\n',
     'From: [email protected]\n',
        'From [email protected] Fri Jan  4 18:10:48 2008\n',
        'From [email protected] Fri Jan  4 16:10:39 2008\n')

for line in L:
    if line.startswith('From'): print(line)
for line in L:
    if 'From' in line: print(line)


From [email protected] Sat Jan  5 09:14:16 2008

From: [email protected]

From [email protected] Fri Jan  4 18:10:48 2008

From [email protected] Fri Jan  4 16:10:39 2008

From [email protected] Sat Jan  5 09:14:16 2008

From: [email protected]

From [email protected] Fri Jan  4 18:10:48 2008

From [email protected] Fri Jan  4 16:10:39 2008


2022-09-21 22:08

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.