如何使用 str.format 禁止换行

How to Suppress Linefeed Using str.format

我知道如何使用 end="" 和 Python 3.0 中的 print 函数来抑制换行,但是如何在使用 str.format 时抑制换行方法?

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

换行符是由 print 函数添加的,而不是 str.format。来自 docs:

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

Print objects to the text stream file, separated by sep and followed by end.

注意 end 参数如何默认为 '\n'(换行符)。 str.format 无法删除此换行符,因为它直到 之后 格式化字符串才提供给 print.

您将需要使用 end="":

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