Python,如何在没有换行符或空格的情况下进行打印?

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函数接受更多参数,例如endend参数用于指定行结束符。 我们将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
Change separator
Change separator
更换分隔符
LEARN MORE  Linux /dev/null Explanation
了解更多Linux / dev / null解释

翻译自: https://www.poftut.com/python-how-to-print-without-newline-or-space/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值