Trong Python 3, print[]
hiện là một hàm và sử dụng các đối số để kiểm soát đầu ra của nó. Trong bài học này, bạn sẽ tìm hiểu về các đối số sep
, end
và flush
.print[]
is now a function and uses arguments to control its output. In this lesson, you’ll learn about the sep
, end
, and flush
arguments.
Theo mặc định, print[]
chèn một khoảng trống giữa các mục mà nó đang in. Bạn có thể thay đổi điều này bằng cách sử dụng tham số sep
:
>>>
>>> print['There are', 6, 'members of Monty Python']
There are 6 members of Monty Python
>>> message = 'There are' + 6 + 'members of Monty Python'
Traceback [most recent call last]:
File "", line 1, in
TypeError: can only concatenate str [not "int"] to str
>>> message = 'There are' + str[6] + 'members of Monty Python'
>>> print[message]
There are6members of Monty Python
>>> print['There are', 6, 'members of Monty Python', sep='😀']
There are😀6😀members of Monty Python
>>> print['There are', 6, 'members of Monty Python', sep=' ']
There are 6 members of Monty Python
>>> print['There are', 6, 'members of Monty Python', sep=None]
There are 6 members of Monty Python
>>> print['There are', 6, 'members of Monty Python', sep='']
There are6members of Monty Python
>>> print['There are', 6, 'members of Monty Python', sep='\n']
There are
6
members of Monty Python
>>> data = [
... ['year', 'last', 'first'],
... [1943, 'Idle', 'Eric'],
... [1939, 'Cleese', 'John']
... ]
>>> for row in data:
... print[*row, sep=',']
...
year,last,first
1943,Idle,Eric
1939,Cleese,John
Trừ khi được nói khác, print[]
thêm một \n
vào cuối những gì đang được in. Điều này có thể được thay đổi với tham số end
. Đầu ra từ print[]
đi vào một bộ đệm. Khi bạn thay đổi tham số end
, bộ đệm không còn bị xóa. Để đảm bảo rằng bạn nhận được đầu ra ngay khi print[]
được gọi, bạn cũng cần sử dụng tham số
import time
def count_items[items]:
print['Counting ', end='', flush=True]
num = 0
for item in items:
num += 1
time.sleep[1]
print['.', end='', flush=True]
print[f'\nThere were {num} items']
4:import time
def count_items[items]:
print['Counting ', end='', flush=True]
num = 0
for item in items:
num += 1
time.sleep[1]
print['.', end='', flush=True]
print[f'\nThere were {num} items']
Bạn có thể kết hợp sep
và end
để tạo danh sách, đầu ra CSV, danh sách viên đạn và hơn thế nữa.