samir
samir

Reputation: 809

Can someone help fix my code?

So here is my code:

with open('lines.txt') as f:
for i in f:
    line = input('line: ')
    if line not in i.split('\n'):
        print(line, i.split('\n'), end='\n')
    else:
        continue

It's supposed to fetch lines from a text file and ask me to type the first, second, third, etc. Until there are no more lines in the file, and if I get a line wrong, it prints 'No!' but it says 'No!' for every single input I enter, so what do I have to do to make this code work?

Upvotes: 1

Views: 271

Answers (4)

user2736953
user2736953

Reputation: 156

Are you supposed to just match the whole line? In which case all you want is

if line != i.strip():

If you need to ignore double spaces etc. It is more complicated, you will need to do the following:

match = True
myWords = line.strip().split()
fileWords = i.strip().split()
for myWord, fileWord in zip(myWords, fileWords):
  if myWord != fileWord:
    match = False
if Match:
  line = input('line: ')
else:
  print('No')

Does the problem require you not to move onto the next line if you get an error??

Upvotes: 1

Joe
Joe

Reputation: 28376

You are comparing a string to a list in the line

    if line != i.split('\n')[0]:

You could try comparing to the first element in the array:

    if line != i.split('\n')[0]:

Or if you can safely ignore leading and trailing spaces:

    if line != i.strip()

The else block you have will present a second, unchecked input after every correctly entered line, was that what you intended?

Upvotes: 1

Shashank
Shashank

Reputation: 13869

Nice try! Here is a solution using the useful rstrip method of string to take care of those pesky newline characters. This does what you want, asking for input line by line, and if you get it wrong, it moves onto the next one.

with open('lines.txt') as f:
    for i in f:
        i = i.rstrip()
        line = input('line: ')
        if line != i:
            print('No!')

Upvotes: 4

TerryA
TerryA

Reputation: 60024

.split() returns a list. You probably meant to check whether the line is in the list.

Do:

if line in i.split('\n'):

Upvotes: 3

Related Questions