[英]How can I print something, and then call a function with a print on the same line?
In Python I have a function that prints something. 在Python中,我有一个打印东西的功能。 I want to print something beforehand on the same line. 我想事先在同一行上打印一些东西。
So, I use the following code 所以,我使用以下代码
print 'The hand is', displayHand(hand)
def displayHand(hand):
for letter in hand.keys():
for j in range(hand[letter]):
print letter, # print all on the same line
print # print an empty line
What happens however is that the print within the function is called by the print outside the function. 然而,会发生的是函数内的打印由函数外部的打印调用。
How can I print an opening string, and then call my function? 如何打印开始字符串,然后调用我的函数?
将displayHand
重命名为renderHand
并让它返回一个字符串。
The answer provided by @zmbq with returning is the obvious and proper one but if you still want your way you can use newer print
, assuming you are using python >= 2.6 @zmbq提供的返回答案是显而易见的,但如果你仍然想要你的方式,你可以使用更新的print
,假设你使用的是python> = 2.6
from __future__ import print_function
print("Something", end="")
With that you can print without \\n
. 有了这个你就可以打印而没有\\n
。 So basically you can do then: 所以基本上你可以做到:
print("The hand is", end="")
displayHand(hand)
And in the function: 并在功能:
print("letter", end="")
For 2.x: 对于2.x:
print 'The hand is',
displayHand(hand)
print
For 3.x: 对于3.x:
print('The hand is', end="")
displayHand(hand)
print()
The better method is to move printing of 'The hand is' into the function itself. 更好的方法是将“手是”打印到功能本身。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.