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

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

先看源码:

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

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

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

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

input ()

先看源码!

    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()会把结尾的换行符也算进去。

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

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

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

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()没有这个功能。

原文地址:https://www.cnblogs.com/HoneyTYX/p/9622476.html