Code leaving random string at end of output

Question:

So i have made the code and it all checks out but when i run it, you would have to create your own text file, i get the random output of (1, ‘n’). I cant explain it properly because im quite new so i hope the code helps.

I have got what i expected to happen however at the end of every line that is printed to the user, the annoying (1,’n’) appears as well.

Asked By: user11605169

||

Answers:

The file.readline method always returns a string with a trailing newline character (unless it’s at the end of file and the file does not end with a newline character), so you should use the str.rstrip method to remove the trailing newline character before processing the string:

line1 = f.readline().rstrip('n')
Answered By: blhsing
f.readline()

Reads each line in the file, including empty lines, for which it will just return the linebacker (‘n’). Usually you don’t see it because print() handles it automatically, but your function counts this as a separate character. See if you have any empty lines at the end of your file, and just backspace them and save.
Hope this helps.

Answered By: Petru Tanas
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.