python中print和input的底层实现

print

print的底层通过sys.stdout.write() 实现

import sys

print('hello')
print('world')
print(520)
sys.stdout.write('hello')
sys.stdout.write('world')
# sys.stdout.write(520)  # TypeError: write() argument must be str, not int



控制台输出

hello
world
520
helloworld


小结

sys.stdout.write()和print都是向屏幕输出内容,区别在于:

  • sys.stdout.write()没有自动换行,print有
  • sys.stdout.write()只能写入字符串,print可以写入任意数据类型


input

Python3中的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

为什么两个长度不一样呢?这是因为sys.stdin.readline()把结尾的换行符也算进去了,6和hello不在一行也可以证明这一点


sys.stdin.readline()还可以传入参数,指定读取前几个字符

c = sys.stdin.readline(2)
print(c, len(c))

控制台输出

hello
he 2



当传入的参数大于输入的字符的长度时,输出所有字符

c = sys.stdin.readline(10)
print(c, len(c))



控制台输出结果

hello
hello
 6



当传入的参数为负数时,表示获取整行

d = sys.stdin.readline(-3)
print(d, len(d))



控制台输出结果

helloworld
helloworld
 11



当一次没有读取完时,下一次读取将会从上次的结束位置开始,这一点与文件类似

c = sys.stdin.readline(6)
print(c, len(c))

d = sys.stdin.readline(4)
print(d, len(d))



控制台输出结果

helloworld
hellow 6
orld 4



sys.stdin.readline()不能像input一样传入字符串作为提示信息

username = input("username:")

password = sys.stdin.readline("password:")



控制台输出结果

username:robin
Traceback (most recent call last):
  File "D:/input_print.py", line 50, in <module>
    password = sys.stdin.readline("password:")
TypeError: 'str' object cannot be interpreted as an integer


小结

sys.stdin.readline()和input都是输入内容,区别在于:

  • sys.stdin.readline()读取所有字符,包括结尾的换行符
  • sys.stdin.readline()可以设置单次读取的字符个数,iinput不行
  • sys.stdin.readline()不能设置提示信息,input可以

猜你喜欢

转载自www.cnblogs.com/zzliu/p/10630437.html