• 技术文章 >常见问题 >Python常见问题

    python输出函数叫什么

    silencementsilencement2019-08-16 14:50:32原创3514

    在编程实践中,print 的使用频率非常高,特别是程序运行到某个时刻,要检测产生的结果时,必须用 print 来打印输出。

    关于 print 函数,前面很多地方已经提及过,可用于写入标准输出。现在,是时候该深入了。

    注意:这里强调的是“print 函数”,而不是“print 语句”。

    深入print

    在 Python 2.x 中,print 是一个语句,但是在 Python 3.x 中,它是一个函数。如果 2.x 和 3.x 都使用过,你就会发现差异有多么大。

    进入 3.x 的交互式 shell,尝试使用“print 语句”:

    [wang@localhost ~]$ python
    Python 3.5.2 (default, Mar 29 2017, 11:05:07) 
    [GCC 4.8.5 20150623 (Red Hat 4.8.5-11)] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> 
    >>> print 'Python'
    ...
    SyntaxError: Missing parentheses in call to 'print'

    对于大多数人来说,这个错误信息再熟悉不过了。正如上面所提到的那样,print 是 3.x 中的一个函数,与其他函数一样,参数应该被圆括号括起来

    >>> print('Python')
    Python

    print函数

    要了解 print 函数的用途,可以使用 help() 来寻求帮助:

    >>> 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.

    将对象输出到文本流文件,由 sep 分开,然后以 end 结束。如果 sep、end、file 和 flush 出现,则必须以关键字参数的形式指定。

    不使用关键字参数

    print 函数可以打印任意数量的值(value1, value2, …),这些值由逗号分隔。

    >>> age = 18
    >>> 
    >>> print('age', age)
    age 18

    很容易发现,两个值之间有一个分隔符 - 空格(默认值),这取决于 sep。

    分隔符

    如果要重新定义分隔符,可以通过 sep 来指定。

    >>> print('age', age, sep='')  # 去掉空格
    age18
    >>> 
    >>> print('www', 'python', 'org', sep='.')  # 以 . 分割
    www.python.org
    专题推荐:输出函数
    品易云
    上一篇:python怎么打印字符串长度 下一篇:什么是Python web框架

    相关文章推荐

    • python里self是什么• Python列表怎么倒序• python怎么运行函数

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网