打印声明后如何取消换行符?
发布于 2021-01-29 15:06:05
我读到这是为了在打印语句后取消换行符,您可以在文本后加上逗号。这里的示例看起来像Python2。
如何在Python 3中完成呢?
例如:
for item in [1,2,3,4]:
print(item, " ")
需要更改什么以便将它们打印在同一行上?
关注者
0
被浏览
88
1 个回答
-
问题问:“ 如何在Python 3中完成? ”
在Python 3.x中使用以下结构:
for item in [1,2,3,4]: print(item, " ", end="")
这将生成:
1 2 3 4
有关更多信息,请参见此Python文档:
Old: print x, # Trailing comma suppresses newline New: print(x, end=" ") # Appends a space instead of a newline
-
除了 :
此外,该
print()
功能还提供了sep
一个参数,该参数使您可以指定应分开打印的单个项目。例如,In [21]: print('this','is', 'a', 'test') # default single space between items this is a test In [22]: print('this','is', 'a', 'test', sep="") # no spaces between items thisisatest In [22]: print('this','is', 'a', 'test', sep="--*--") # user specified separation this--*--is--*--a--*--test