2017-02-14 72 views
-3

您好,我目前的工作目標,我想打印輸出,例如在pythonPython的打印問題與空間

你好= 10

但我下面的代碼打印出來這樣

你好= 10

10是INT我嘗試了這些代碼,但沒有工作

print "hello=",10 
print "hello=",str(10) 
print "hello=",str(10).strip() 

我將不勝感激幫助謝謝

+0

這僅僅是你的代碼編輯器的可視化方面,它不會影響您正在嘗試執行的功能。你能提供你爲什麼需要這個的背景嗎?你可以試試'print'hello = 10''' –

+2

','形成一個打印分隔空間的元組。而是使用'print'hello =%s「%10」或更現代的「hello = {0}」格式(10)' –

+3

這正是應該發生的事情。當你傳遞多個項目來打印時,將它們分隔開。如果你不想這樣做,建立一個你想要的單個字符串,然後通過它。 – jonrsharpe

回答

3

只需在連接字符串:

print "hello="+str(10) 
3

使用str.format

print("hello={}".format(10)) 

PS:本print聲明已被替換因爲Python 3.0 print()功能。

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

有關詳細說明,請參閱Print Is A Function

1

如果您使用帶有多個參數的print,這些參數之間用,分隔,則會在每個參數之間插入一個空格' '作爲分隔符。

當使用Python 3的print function,您可以指定sep參數;默認爲' '

>>> from __future__ import print_function # when in Python 2 
>>> print("hello=", 10) 
hello= 10 
>>> print("hello=", 10, sep="") 
hello=10 
>>> print("hello=", 10, sep="###") 
hello=###10 

對於Python 2的print statement,還有就是盡我所知沒有這樣的選擇的。

0

您也可以考慮使用Python 3兼容print()功能:

此功能可以在__future__指令後使用:

from __future__ import print_function 

print("hello=", 10, sep='') 

輸出:

hello=10 

print()功能一個關鍵字參數,它允許您更換由空字符串分隔空間。

這裏是在線幫助:

幫助的內置功能打印模塊內建的:

打印(...) 打印(值,... 09月=」' ,end ='\ n',file = sys。標準輸出,沖洗= FALSE)

Prints the values to a stream, or to sys.stdout by default. 
Optional keyword arguments: 
file: a file-like object (stream); defaults to the current sys.stdout. 
sep: string inserted between values, default a space. 
end: string appended after the last value, default a newline. 
flush: whether to forcibly flush the stream. 
0

呼叫 「打印」 將放置一個逗號的空間。

是,Python提供了許多方法來打印字符串作爲上面提到的,我還是想構建的輸出與C或Java風格的格式:

print "hello=%d" % 10