2012-10-24 273 views
2

如果我有一個程序,例如:格式化字符串

def P(x): 
     # x is an integer 
     print str(x) 

,我想有一個輸出,例如:

>>> You chose the number: X 

其中X是印刷過程P內的結果。 如何在不改變程序的情況下做到這一點?

如果我這樣做:

print 'You chose the number: ' 
    P(x) 

我會得到

You chose the number: 
X 

我怎樣才能讓他們在同一行?

回答

6

添加trailing逗號第一print語句後,打印下一條語句在同一行: -

print 'You chose the number: ', 
P(x) 
1

嘗試字符串格式化:

print 'You chose the number: {0}'.format(P(x)) 

和,而不是從打印功能使用return

def P(x): 
     return str(x) 
+1

OP不想改變程序P(x) –

+0

@RohitJain我認爲我錯過了那個部分,但是從函數返回值而不是打印它是一個很好的習慣。 –

+0

是的,在這種情況下,這當然是更好的選擇,特別是當OP除了打印傳遞的值的字符串表示形式之外什麼也不做。 –

1

什麼是

P('You chose the number: ' + str(x)) 
P('You chose the number: {0}'.format(x)) 
P('You chose the number: %s' % x) 

?其他答案表明您不必更改P()