The print function, sep and end are two commonly used parameters in Python programming. SEP is used to specify the separator that should be used when multiple values are printed, while end is used to specify the string that should be printed after all values have been printed.
This article will provide a comprehensive and in-depth introduction to the use of sep and end in Python.
Usage of SEP.
Define the separator.
The sep parameter is used to specify the delimiter that should be used when printing multiple values.
For example, if we want to separate multiple values with a comma, we can set the sep to a comma:
values = [1, 2, 3]print(*values, sep=',')
The output is:
Use an empty string as a delimiter.
If we want to not use any delimiter, we can set the sep to an empty string:
values = ['apple', 'banana', 'cherry']print(*values, sep='')
Output: Applebananacherry
Usage of end.
Define the closing string.
The end parameter is used to specify the string that should be printed after all values have been printed. For example, if we want to add an exclamation mark after all values have been printed, we can set end to an exclamation mark:
values = [1, 2, 3, 4]print(*values, end='!'Output:
Use an empty string as the closing string.
If we want not to add any ending string, we can set end to an empty string:
values = [1, 2, 3, 4, 5]print(*values, end='')
The output is:
Practical application of SEP and END.
Print the elements in the list.
We can use the sep and end parameters to print the elements in the list, and specify the delimiter and closing string.
For example, if we want to separate the list elements with a comma and add an exclamation point, we can do this:
fruits = ['apple', 'banana', 'cherry']print(*fruits, sep=',', end='!')
The output is:
apple,banana,cherry!
Print multiple lines of text.
We can use the sep and end parameters to print multiple lines of text, and specify a delimiter and a closing string. For example, if we want to print multiple lines of text and separate each line of text with a line break, we can do this:
text = "helloworld!"print(text.split(''), sep='', end=''Use line breaks as separators and closing strings, note that end needs to be set to an empty string for line breaks to be displayed correctly.
Summary. By using the sep and end parameters, we have the flexibility to control the format of the output of the print function.
In practical applications, we can use the sep and end parameters to print elements in a list, print multiple lines of text, and other scenarios.