Python: 消除print的自动换行

Python: 消除print换行

标签:python print \n

by 小威威


对于python2.X,要消除print的自动换行,只需在print尾部加上一个逗号”,”,但是这一做法在python3.X就不适用了,这是为什么呢?我们可以在交互式的环境下输入help(print),查询print的原理和使用方法。

Help on built-in function print in module builtins:

print(…)
print(value, …, sep=’ ‘, end=’\n’, file=sys.stdout, flush=False)

appledeMacBook-Pro-2:Desktop apple$ python3
Python 3.5.0 (v3.5.0:374f501f4567, Sep 12 2015, 11:00:19) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> help(print)
Help on built-in function print in module builtins:

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

    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file:  a file-like object (stream); defaults to the current sys.stdout.
    sep:   string inserted between values, default a space.
    end:   string appended after the last value, default a newline.
    flush: whether to forcibly flush the stream.
(END) 

注意看这一句:

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

这一句说明在python3中print是一个函数,对于函数,其形参中有默认参数和关键参数。我们发现,在结尾处出现了end = ‘\n’,说明print是以\n结束的,end是默认参数。只要我们在print中将默认参数的值改为空或者空格,就能实现不换行。

举个栗子:

#!/usr/bin/python3
# Filename: using_list.py

# This is my shopping list

shoplist = ['apple', 'mango', 'carrot', 'banana']
print ('These items are:')
for i in shoplist:
    print (i,end=' ')
# End

输出结果如下:

These items are:
apple mango carrot banana 

以上内容皆为本人观点,欢迎大家提出批评和指导,我们一起探讨。


  • 9
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值