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.
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')
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.
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.
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')
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.