2015-02-05 54 views
1

我知道如何使用end=""和Python 3.0中的print函數來抑制換行,但是如何在使用str.format方法時抑制換行?如何使用str.format抑制換行

print("Hello", end=",") # Works 
print(" Hola") 
print("{}".format("")) 
print("{}".format("Hello", end = ",")) # Doesn't work 
print("{}".format(" Hola")) 
+0

你可能想以獲得有用的答案提供關於這一問題(也可能更多的細節在每個實例)的更多信息。 – Stratus3D 2015-02-05 21:48:42

回答

5

換行符正在由print函數,而不是加入str.format。從docs

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

打印objects文本流file,通過sep分離,隨後end

請注意end參數默認爲'\n'(換行符)。 str.format無法刪除此換行符,因爲之後之後不存在,因此格式化的字符串被賦予print

您將需要使用end=""

print("{}".format("Hello"), end="") 
+0

棒極了。在我將自己置於這裏臭名昭着的版主之前,你不會相信我嘗試過多少種方式。這可能是我沒有試過的唯一組合。謝謝。 – JayJay123 2015-02-05 21:45:39