浅析 python中的 print 和 input 的底层区别!!!

近期的项目中 涉及到相关知识 就来总结一下 !

先看源码:python

def print(self, *args, sep=' ', end='\n', file=None): # known special case of 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.
    """

# 附带翻译哦!
将值打印到溪流或系统中。默认stdout。
可选关键字参数:
文件:相似文件的对象(流);默认为当前的systdout。
sep:在值之间插入字符串,默认空格。
结束:在最后一个值以后附加的字符串,默认换行。
python 源码

 

print()用sys.stdout.write() 实现 app

import sys
 
print('hello')
sys.stdout.write('hello')
print('new')
 
 
# 结果:
# hello
# hellonew

sys.stdout.write()结尾没有换行,而print()是自动换行的。另外,write()只接收字符串格式的参数。ide

print()能接收多个参数输出,write()只能接收一个参数。spa

input ()翻译

先看源码!code

    Read a string from standard input.  The trailing newline is stripped.
    
    The prompt string, if given, is printed to standard output without a
    trailing newline before reading input.
    
    If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
    On *nix systems, readline is used if available.

附带 翻译 

从标准输入中读取一个字符串 a 。后面的新线被剥掉了。
若是给定的话,提示字符串会被打印到标准输出,而不须要a
在阅读输入以前,跟踪新行。
若是用户点击了EOF(nix:Ctrl-D,Windows:Ctrl-Z+Return),就会产生EOFError。
在nix系统上,若是可用,则使用readline。

input 用 sys.stdin.readline() 实现对象

import sys
 
a = sys.stdin.readline()
print(a, len(a))
 
b = input()
print(b, len(b))
 
 
# 结果:
# hello
# hello
#  6
# hello
# hello 5

readline()会把结尾的换行符也算进去。blog

readline()能够给定整型参数,表示获取从当前位置开始的几位内容。当给定值小于0时,一直获取这一行结束。ip

import sys
 
a = sys.stdin.readline(3)
print(a, len(a))
 
 
# 结果:
# hello
# hel 3

readline()若是给定了整型参数结果又没有把这一行读完,那下一次readline()会从上一次结束的地方继续读,和读文件是同样的。ci

import sys
 
a = sys.stdin.readline(3)
print(a, len(a))
 
b = sys.stdin.readline(3)
print(b, len(b))
 
# 结果
# abcde
# abc 3
# de
#  3

 

input()能够接收字符串参数做为输入提示,readline()没有这个功能。

相关文章
相关标签/搜索