file = 'pi'
with open(file) as object:
for line in object:
print(line)
The file content includes the first 30 digits of pi, and I don't understand why it is printing a line after reading a particular line. As in, how can print(line) actually print a line?
The contents of the file are henceforth:
3.1415926535
8979323846
2643383279
And this is the output:
3.1415926535
8979323846
2643383279
CodePudding user response:
Because by default, print add a newline after a print, you can change this by adding the end parameter to your print statement :
print(line, end='')
CodePudding user response:
Print function takes many parameters. One relevant here is end. Default value is '\n'
try print(line, end='')
CodePudding user response:
This is because each row in your datafile is appended with a newline character, \n. If you want to remove this from your line, you can do
line = line.rstrip()
If you want to print without the newline character, change the args to print as
print(line, end='')
CodePudding user response:
The line strings that you are looping include a newline character at the end ("\n"), and print also adds a newline after the call, so you have two. Instead, you can strip the newline character before printing:
file = 'pi'
with open(file) as object:
for line in object:
print(line.strip("\n"))
CodePudding user response:
According to the documentation provided here:
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
Print objects to the text stream file, separated by sep and followed by end. sep, end, file, and flush, if present, must be given as keyword arguments.
If no parameters are provided, end parameter takes "\n" by default.
So, you could print the lines like:
print(line, end='')
