¿Cómo imprimir sin nueva línea o espacio?


La pregunta está en el título.

Me gustaría hacerlo en python. Lo que me gustaría hacer en este ejemplo en c:

#include <stdio.h>

int main() {
    int i;
    for (i=0; i<10; i++) printf(".");
    return 0;
}

Salida:

..........

En Python:

>>> for i in xrange(0,10): print '.'
.
.
.
.
.
.
.
.
.
.
>>> for i in xrange(0,10): print '.',
. . . . . . . . . .

En Python print agregará un \n o un espacio, ¿cómo puedo evitar eso? Ahora, es solo un ejemplo. No me digas que primero puedo construir una cadena y luego imprimirla. Me gustaría saber cómo "anexar" cadenas a stdout.

 1436

25 answers

Vía general

import sys
sys.stdout.write('.')

Es posible que también tenga que llamar a

sys.stdout.flush()

Para asegurar que stdout se enjuague inmediatamente.

Python 2.6 +

Desde Python 2.6 puede importar la función print desde Python 3:

from __future__ import print_function

Esto le permite utilizar la solución de Python 3 a continuación.

Python 3

En Python 3, la instrucción print se ha cambiado a una función. En Python 3, puedes hacer:

print('.', end='')

Esto también funciona en Python 2, siempre que has usado from __future__ import print_function.

Si tiene problemas con el almacenamiento en búfer, puede vaciar la salida agregando flush=True argumento de palabra clave:

print('.', end='', flush=True)

Sin embargo, tenga en cuenta que la palabra clave flush no está disponible en la versión de la función print importada desde __future__ en Python 2; solo funciona en Python 3, más específicamente 3.3 y posteriores. En versiones anteriores, todavía tendrá que vaciar manualmente con una llamada a sys.stdout.flush().

 1971
Author: codelogic,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-03 15:25:12

Debe ser tan simple como se describe en este enlace por Guido Van Rossum:

Re: ¿Cómo se imprime sin c/r ?

Http://legacy.python.org/search/hypermail/python-1992/0115.html

¿Es posible imprimir algo pero no tener automáticamente un ¿retorno de carro adjunto ?

Sí, añada una coma después del último argumento a imprimir. Por ejemplo, este bucle imprime los números 0..9 en una línea separada por espacios. Nota el "print" sin parámetros que añade la nueva línea final:

>>> for i in range(10):
...     print i,
... else:
...     print
...
0 1 2 3 4 5 6 7 8 9
>>> 
 278
Author: KDP,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-09 01:04:42

Nota: El título de esta pregunta solía ser algo así como " How to printf in python?"

Dado que la gente puede venir aquí buscándolo basado en el título, Python también admite la sustitución de estilo printf:

>>> strings = [ "one", "two", "three" ]
>>>
>>> for i in xrange(3):
...     print "Item %d: %s" % (i, strings[i])
...
Item 0: one
Item 1: two
Item 2: three

Y, puede multiplicar fácilmente los valores de cadena:

>>> print "." * 10
..........
 157
Author: Beau,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-12-20 19:02:29

Utilice la función de impresión de estilo python3 para python2.6+ (también romperá cualquier sentencia de impresión con palabras clave existente en el mismo archivo.)

# for python2 to use the print() function, removing the print keyword
from __future__ import print_function
for x in xrange(10):
    print('.', end='')

Para no arruinar todas sus palabras clave de impresión python2, cree un archivo printf.py separado

# printf.py

from __future__ import print_function

def printf(str, *args):
    print(str % args, end='')

Luego, úsalo en tu archivo

from printf import printf
for x in xrange(10):
    printf('.')
print 'done'
#..........done

Más ejemplos que muestran el estilo printf

printf('hello %s', 'world')
printf('%i %f', 10, 3.14)
#hello world10 3.140000
 86
Author: k107,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-04-28 07:33:19

Esta no es la respuesta a la pregunta en el título, pero es la respuesta sobre cómo imprimir en la misma línea:

import sys
for i in xrange(0,10):
   sys.stdout.write(".")
   sys.stdout.flush()
 38
Author: lenooh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-12-03 17:16:00

La nueva función (a partir de Python 3.0) print tiene un parámetro opcional end que le permite modificar el carácter final. También hay sep para separador.

 23
Author: SilentGhost,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-12 14:01:55

Simplemente puede agregar , al final de la función print para que no se imprima en una nueva línea.

 16
Author: user3763437,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-10 19:45:40

Usando functools.partial para crear una nueva función llamada printf

>>> import functools

>>> printf = functools.partial(print, end="")

>>> printf("Hello world\n")
Hello world

Forma fácil de envolver una función con parámetros predeterminados.

 14
Author: sohail288,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-17 01:55:02

print la función en python genera automáticamente una nueva línea. Puedes probar:

print("Hello World", end="")

 13
Author: klee8_,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-14 19:17:53

Puedes hacerlo con end argumento de print. En Python3, range() devuelve el iterador y xrange() no existe.

for i in range(10): print('.', end='')
 9
Author: Maxim,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-23 09:59:27

Código para Python 3.6.1

for i in range(0,10): print('.' , end="")

Salida

..........
>>>
 8
Author: Jasmohan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-03 17:14:21

Puedes probar:

import sys
import time
# Keeps the initial message in buffer.
sys.stdout.write("\rfoobar bar black sheep")
sys.stdout.flush()
# Wait 2 seconds
time.sleep(2)
# Replace the message with a new one.
sys.stdout.write("\r"+'hahahahaaa             ')
sys.stdout.flush()
# Finalize the new message by printing a return carriage.
sys.stdout.write('\n')
 7
Author: alvas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-11-23 12:03:31

Desea imprimir algo en for loop a la derecha;pero no quiere que se imprima en una nueva línea cada vez.. por ejemplo:

 for i in range (0,5):
   print "hi"

 OUTPUT:
    hi
    hi
    hi
    hi
    hi

Pero quieres que se imprima así: hi hi hi hi hi hi derecho???? simplemente agregue una coma después de imprimir"hi"

Ejemplo:

for i in range (0,5): print "hi", OUTPUT: hi hi hi hi hi

 6
Author: Bala.K,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-07 12:12:32

En Python 3, la impresión es una función. Cuando llamas

print ('hello world')

Python lo traduce a

print ('hello world', end = '\n')

Puedes cambiar end a lo que quieras.

print ('hello world', end = '')
print ('hello world', end = ' ')
 6
Author: Yaelle,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-10 01:36:32
for i in xrange(0,10): print '.',

Esto funcionará para ti. aquí la coma (,) es importante después de imprimir. Recibió ayuda de: http://freecodeszone.blogspot.in/2016/11/how-to-print-in-python-without-newline.html

 5
Author: Shekhar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-13 12:28:38

Puedes hacer lo mismo en python3 de la siguiente manera :

#!usr/bin/python

i = 0
while i<10 :
    print('.',end='')
    i = i+1

Y ejecutarlo con python filename.py o python3 filename.py

 4
Author: Subbu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-05 17:37:06

@lenooh satisfizo mi consulta. Descubrí este artículo mientras buscaba 'python suppress newline'. Estoy usando IDLE3 en Raspberry Pi para desarrollar Python 3.2 para PuTTY. Quería crear una barra de progreso en la línea de comandos de PuTTY. No quería que la página se desplazara. Quería una línea horizontal para volver a asegurar que el usuario se asuste de que el programa no se ha detenido ni ha sido enviado a almorzar en un alegre bucle infinito , como una súplica para ' déjame en paz, estoy bien, pero esto puede tomar algún tiempo.'mensaje interactivo-como una barra de progreso en el texto.

El print('Skimming for', search_string, '\b! .001', end='') inicializa el mensaje preparándose para la siguiente escritura de pantalla, que imprimirá tres espacios atrás como rub rubout y luego un punto, borrando '001' y extendiendo la línea de puntos. Después de la entrada del usuario search_string parrots, el \b! recorta el signo de exclamación de mi search_string texto para retroceder sobre el espacio que print() de otra manera fuerza, colocando correctamente la puntuación. Que es seguido por un espacio y el primer 'punto' de la 'barra de progreso' que estoy simulando. Innecesariamente, el mensaje también se prepara con el número de página (formateado a una longitud de tres con ceros a la izquierda) para tomar nota del usuario de que el progreso se está procesando y que también reflejará el recuento de puntos que más tarde construiremos a la derecha.

import sys

page=1
search_string=input('Search for?',)
print('Skimming for', search_string, '\b! .001', end='')
sys.stdout.flush() # the print function with an end='' won't print unless forced
while page:
    # some stuff…
    # search, scrub, and build bulk output list[], count items,
    # set done flag True
    page=page+1 #done flag set in 'some_stuff'
    sys.stdout.write('\b\b\b.'+format(page, '03')) #<-- here's the progress bar meat
    sys.stdout.flush()
    if done: #( flag alternative to break, exit or quit)
        print('\nSorting', item_count, 'items')
        page=0 # exits the 'while page' loop
list.sort()
for item_count in range(0, items)
    print(list[item_count])
#print footers here
 if not (len(list)==items):
    print('#error_handler')

La carne de la barra de progreso está en la línea sys.stdout.write('\b\b\b.'+format(page, '03')). Primero, para borrar a la izquierda, hace una copia de seguridad del cursor sobre los tres caracteres numéricos con el '\b\b\b ' como rub rubout y drops un nuevo período para agregar a la longitud de la barra de progreso. Luego escribe tres dígitos de la página a la que ha progresado hasta ahora. Debido a que sys.stdout.write() espera que se cierre un búfer completo o el canal de salida, sys.stdout.flush() fuerza la escritura inmediata. sys.stdout.flush() se construye al final de print() que se omite con print(txt, end='' ). Luego, el código recorre sus operaciones mundanas intensivas en tiempo mientras no imprime nada más hasta que regresa aquí para borrar tres dígitos, agregar un punto y escribir tres dígitos nuevamente, incrementar.

Los tres dígitos borrados y reescritos de ninguna manera son necesarios - es solo un florecimiento que ejemplifica sys.stdout.write() versus print(). Usted podría igual de fácilmente cebar con un punto y olvidar los tres elegantes espacios inversos-b back (por supuesto, no escribir cuentas de página formateadas también) simplemente imprimiendo la barra de período más larga por uno cada vez - sin espacios o nuevas líneas usando solo el par sys.stdout.write('.'); sys.stdout.flush().

Tenga en cuenta que el shell python de Raspberry Pi IDLE3 no honre el retroceso como rub rubout pero en su lugar imprime un espacio, creando una lista aparente de fracciones en su lugar.

- (o = 8> wiz

 4
Author: DisneyWizard,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-01 23:19:25

Python 2.6+:

from __future__ import print_function # needs to be first statement in file
print('.', end='')

Python 3:

print('.', end='')

Python 2.5:

import sys
sys.stdout.write('.')

Si el espacio adicional está bien después de cada impresión, en python 2

print '.',

Engañoso en python 2 - evitar :

print('.'), # avoid this if you want to remain sane
# this makes it look like print is a function but it is not
# this is the `,` creating a tuple and the parentheses enclose an expression
# to see the problem, try:
print('.', 'x'), # this will print `('.', 'x') `
 4
Author: n611x007,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-22 17:09:59

Recientemente tuve el mismo problema..

Lo resolví haciendo:

import sys, os

# reopen stdout with "newline=None".
# in this mode,
# input:  accepts any newline character, outputs as '\n'
# output: '\n' converts to os.linesep

sys.stdout = os.fdopen(sys.stdout.fileno(), "w", newline=None)

for i in range(1,10):
        print(i)

Esto funciona tanto en unix como en Windows ... no lo han probado en macosx ...

Hth

 4
Author: ssgam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-17 19:59:40

Usted notará que todas las respuestas anteriores son correctas. Pero quería hacer un atajo para escribir siempre el parámetro" end= "" al final.

Podría definir una función como

def Print(*args,sep='',end='',file=None,flush=False):
    print(*args,sep=sep,end=end,file=file,flush=flush)

Aceptaría todo el número de parámetros. Incluso aceptará todos los otros parámetros como file, flush, etc y con el mismo nombre.

 4
Author: Bikram Kumar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-09 05:54:20

Muchas de estas respuestas parecen un poco complicadas. En Python 3.X simplemente haga esto,

print(<expr>, <expr>, ..., <expr>, end=" ")

El valor predeterminado de end es "\n". Simplemente lo estamos cambiando a un espacio o también puede usar end="".

 3
Author: jarr,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-11-24 18:46:28
for i in xrange(0,10): print '\b.',

Esto funcionó tanto en 2.7.8 como en 2.5.2 (Canopy y terminal OSX, respectivamente) no no se requieren importaciones de módulos ni viajes en el tiempo.

 3
Author: tyersome,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-18 21:13:00

Esta es una forma general de imprimir sin insertar una nueva línea.

Python 3

for i in range(10):
  print('.',end = '')

En Python 3 es muy sencillo implementar

 1
Author: Steffi Keran Rani J,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-10 08:51:44

...no es necesario importar ninguna biblioteca. Simplemente use el carácter delete:

BS=u'\0008' # the unicode for "delete" character
for i in range(10):print(BS+"."),

Esto elimina la nueva línea y el espacio (^ _ ^) *

 0
Author: mchrgr2000,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-17 04:50:57

Hay dos formas generales de hacer esto:

Imprimir sin nueva línea en Python 3.x

No añada nada después de la instrucción print y elimine '\n ' usando end='' como:

>>> print('hello')
hello  # appending '\n' automatically
>>> print('world')
world # with previous '\n' world comes down

# solution is:
>>> print('hello', end='');print(' world'); # end with anything like end='-' but not '\n'
hello world # it seem correct output

Otro ejemplo en Loop :

for i in range(1,10):
    print(i, end='.')

Imprimir sin nueva línea en Python 2.x

Añadiendo una coma final después de imprimir ignore '\n'.

>>> print "hello",; print" world"
hello world

Otro ejemplo en Loop :

for i in range(1,10):
    print "{} .".format(i),

Espero que esto te ayude. Puedes visitar este link .

 0
Author: Sushant,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-20 13:35:42