Last Updated:

Print function and sep parameter in Python

 

The print function allows you to display text on the screen. The recording pattern of this function is as follows:

print(*items,sep=’ ‘,end=’\n’,file=sys.stdout,flush=False);

All arguments to the print function are key, that is, they are passed with their name before the "=" symbol. You can transfer them in any order.

  • *items – objects to be displayed.
  • sep – object separator.
  • end – symbols placed after all objects.
  • file—Selects the file to output.
  • flush—Manages the switching of buffering to a file.

Learn more about feature options

end

By default, the value of the end parameter is "/n". If you do not specify this parameter, a line wrap occurs after the print function is called. An example of using print without specifying the end parameter:

Code:>>> print(1, "Text 1", 2)
Output: 1 Text1 2

If you specify the end parameter as empty, there will be no transition to a new line.

Code:>>>print(1, "Text 2", 2, end=")
Output: 1 Text 2>>>

You can specify multiple characters in a parameter value by using concatenation.

Code:>>>print(1, Text 3, 2, end='\n'+'-'*5 +'\n')
Output: 1 Text 3 2

file

The default value of the file parameter is sys.stdout, which is the standard output stream. You can also assign this parameter to the file to which the output will occur. Example of outputting text to a file:

Code:f = open('testfile.txt', 'w')
fori in range(5):
print(f'Number {i}', file=f)
f.close()

Withdrawal:Number 0 //recorded in the file testfile.txt
Number 1
Number 2
Number 3
Number 4

flush

Flush is a Boolean parameter with a default value of False. You can use it to disable buffering. For the sleep function from the time module to work correctly, you must set the flush parameter to True. An example of its use:

Code:import time
fori in range(5):
print('Number ', i, flush=True)
time.sleep(2)

Conclusion: Number 0
Number 1//each line is displayed 2 seconds after the
previous Number 2
Number 3
Number 4

sep

The default value of the sep parameter is a space. Sep can be applied to a date entry for example:

Code:print(23, «03», 2021, sep='.')
Conclusion:23.03.2021

Just like in the end parameter, you can use string concatenation here. An example of such use:

Code:print(1, "Str", 2, sep='\n'+'-'*5 +'\n')
Output:1
——
Str
——
2