Как я могу подавить новую строку после заявления печати?
Я прочитал, что для подавления новой строки после оператора печати вы можете поместить запятую после текста. Пример здесь выглядит как Python 2. Как это можно сделать в Python 3?
Например:
for item in [1,2,3,4]:
print(item, " ")
Что нужно изменить, чтобы он печатал их в одной строке?
Ответы
Ответ 1
Вопрос задает вопрос: " Как это сделать в Python 3?"
Используйте эту конструкцию с Python 3.x:
for item in [1,2,3,4]:
print(item, " ", end="")
Это будет генерировать:
1 2 3 4
Дополнительную информацию см. в документе Python:
Old: print x, # Trailing comma suppresses newline
New: print(x, end=" ") # Appends a space instead of a newline
-
Помимо
Кроме того, функция print()
также предлагает параметр sep
, который позволяет указать, как отдельные элементы, подлежащие печати, должны быть разделены. Например.
In [21]: print('this','is', 'a', 'test') # default single space between items
this is a test
In [22]: print('this','is', 'a', 'test', sep="") # no spaces between items
thisisatest
In [22]: print('this','is', 'a', 'test', sep="--*--") # user specified separation
this--*--is--*--a--*--test
Ответ 2
print не переходил из оператора в функцию до Python 3.0. Если вы используете более старый Python, вы можете подавить новую строку с помощью конечной запятой, например:
print "Foo %10s bar" % baz,
Ответ 3
Код для Python 3.6.1
print("This first text and " , end="")
print("second text will be on the same line")
print("Unlike this text which will be on a newline")
Выход
>>>
This first text and second text will be on the same line
Unlike this text which will be on a newline
Ответ 4
Поскольку функция python 3 print() позволяет определить end = "", что удовлетворяет большинству вопросов.
В моем случае я хотел PrettyPrint и был разочарован тем, что этот модуль не был так обновлен. Поэтому я сделал так, чтобы я хотел:
from pprint import PrettyPrinter
class CommaEndingPrettyPrinter(PrettyPrinter):
def pprint(self, object):
self._format(object, self._stream, 0, 0, {}, 0)
# this is where to tell it what you want instead of the default "\n"
self._stream.write(",\n")
def comma_ending_prettyprint(object, stream=None, indent=1, width=80, depth=None):
"""Pretty-print a Python object to a stream [default is sys.stdout] with a comma at the end."""
printer = CommaEndingPrettyPrinter(
stream=stream, indent=indent, width=width, depth=depth)
printer.pprint(object)
Теперь, когда я это сделаю:
comma_ending_prettyprint(row, stream=outfile)
Я получаю то, что я хотел (замените то, что вы хотите - ваш пробег мая может)