python中input和print的区别_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

控制台输出

```python

hello

world

520

helloworld

## 小结

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

- sys.stdout.write()没有自动换行,print有

- sys.stdout.write()只能写入字符串,print可以写入任意数据类型

## input

Python3中的input()使用`sys.stdin.readline()`实现

```python

import sys

a = sys.stdin.readline()

print(a, len(a))

b = input()

print(b, len(b))

控制台输出结果

```python

hello

hello

6

hello

hello 5

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

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

```python

c = sys.stdin.readline(2)

print(c, len(c))

控制台输出

hello

he 2

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

```python

c = sys.stdin.readline(10)

print(c, len(c))

控制台输出结果

```python

hello

hello

6

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

```python

d = sys.stdin.readline(-3)

print(d, len(d))

控制台输出结果

```python

helloworld

helloworld

11

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

```python

c = sys.stdin.readline(6)

print(c, len(c))

d = sys.stdin.readline(4)

print(d, len(d))

控制台输出结果

```python

helloworld

hellow 6

orld 4

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

```python

username = input("username:")

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

控制台输出结果

```python

username:robin

Traceback (most recent call last):

File "D:/input_print.py", line 50, in

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可以

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值