I have a simple problem with python about new line while printing. How can I print without newline or space? In python print
will add at the end of the given string data \n
newline or a space. But in this situation we do not will use append
string to stdout
.
我在打印时对python有一个关于换行的简单问题。 如何在没有换行符或空格的情况下进行打印? 在python中, print
将在给定字符串数据的末尾添加\n
换行符或空格。 但是在这种情况下,我们不会将append
字符串用于stdout
。
Python2 (Python2)
We generally prefer Python 3 in our posts but there are some people who uses python2 too so in this situation we will provide python2 way solution. We will import sys
and use stdout.write
functions and flush
given data to the stdout without a newline.
我们通常在帖子中更喜欢Python 3,但也有人使用python2,因此在这种情况下,我们将提供python2方式的解决方案。 我们将导入sys
并使用stdout.write
函数,并将给定的数据flush
到stdout而不使用换行符。
import sys
sys.stdout.write('asdf')
sys.stdout.flush()
Another way is if we are using python2.6 and above we can use python3 solution like below.
另一种方法是,如果我们使用的是python2.6及更高版本,则可以使用如下所示的python3解决方案。
Python3 (Python3)
Python 3 provides simple and convenient solution for this issue. print
function provides more than string to be printed. print
function accepts more parameters like end
. end
parameter is used to specify the line end character. We will set end
option to nothing and this will remove default \n
or end of line or space.
Python 3为这个问题提供了简单方便的解决方案。 print
功能提供的不仅仅是字符串。 print
函数接受更多参数,例如end
。 end
参数用于指定行结束符。 我们将end
选项设置为空,这将删除默认\n
或行尾或空格。
print('this is a string', end="")
print(' and this is on the same line')
更换分隔符 (Change separator)
Another way to remove spaces in multiple print argument is using sep
option of the print
function. We can specify any character as separator. In this example we use empty string as separator which will join two string together.
删除多个打印参数中的空格的另一种方法是使用print
函数的sep
选项。 我们可以指定任何字符作为分隔符。 在此示例中,我们使用空字符串作为分隔符,它将两个字符串连接在一起。
print("Hi","Poftut")
#Hi Poftut
print("Hi","Poftut",sep='')
#HiPoftut
翻译自: https://www.poftut.com/python-how-to-print-without-newline-or-space/