2012-08-24 12 views
44

Ho letto che per sopprimere la nuova riga dopo un'istruzione di stampa è possibile inserire una virgola dopo il testo. L'esempio here somiglia a Python 2. Come può essere fatto in Python 3?Come posso sopprimere la nuova riga dopo una dichiarazione di stampa?

Ad esempio:

for item in [1,2,3,4]: 
    print(item, " ") 

Che cosa deve cambiare in modo che li stampa sulla stessa linea?

+1

Si può solo fare 'di stampa ('' .join ([str (i) for i in [1, 2, 3, 4]]))' ' –

+0

di stampa (* [1, 2, 3, 4]) 'funziona per il caso comune di stampare una sequenza separata dallo spazio –

risposta

82

La domanda chiede: "Come può essere fatto in Python 3?"

Utilizzare questo costrutto con Python 3.x:

for item in [1,2,3,4]: 
    print(item, " ", end="") 

Questo genererà:

1 2 3 4 

Vedere questo Python doc per ulteriori informazioni:

Old: print x,   # Trailing comma suppresses newline 
New: print(x, end=" ") # Appends a space instead of a newline 

-

parte:

in aggiunta, la funzione print() offre anche il parametro sep che permette un specificare in che modo i singoli elementi da stampare dovrebbero essere separati. Ad esempio,

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 
+1

Perfetto! Quindi end = "" sovrascrive il carattere di nuova riga. – Ci3

+0

@ChrisHarris Vedi l'aggiornamento con la citazione dai documenti, quindi stai sostituendo la nuova riga con '" "' (la stringa vuota) – Levon

+1

Molto utile, grazie! – Ci3

4

stampa non ha passato da istruzione a funzione fino a Python 3.0. Se stai usando più vecchio di Python allora si può sopprimere il ritorno a capo con una virgola finale in questo modo:

print "Foo %10s bar" % baz, 
+4

La domanda specificamente posta sull'uso di Python 3. –

0

Perché Python 3 print() funzione permette end = "" definizione, che soddisfa la maggior parte dei problemi.

Nel mio caso, volevo PrettyPrint ed ero frustrato dal fatto che questo modulo non fosse stato aggiornato in modo simile. Così ho fatto fare quello che volevo:

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) 

Ora, quando faccio:

comma_ending_prettyprint(row, stream=outfile) 

ottengo quello che volevo (sostituto ciò che si vuole - La vostra situazione potrebbe essere diversa)

3

codice per 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") 

uscita

>>> 
This first text and second text will be on the same line 
Unlike this text which will be on a newline 
+0

Questo chiarito come il parametro end = "" influenzerebbe la riga successiva, ma non quella successiva - grazie! –

Problemi correlati