-
input()和print()是python的输入输出函数
>>> x = input('Please input:')
Please input:546
>>> x
'546'
>>> type(x) # 把用户的输入作为字符串对待
<class 'str'>
>>> int(x)
546
>>> eval(x) # 对字符串求值,或类型转换
546
>>> x = input('Please input:')
Please input:[1, 2, 3]
>>> x
'[1, 2, 3]'
>>> eval(x)
[1, 2, 3]
>>> x = input('Please input:')
Please input:hello world
>>> x
'hello world'
>>> eval(x)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1
hello world
^
SyntaxError: unexpected EOF while parsing
>>> x = input('Please input:')
Please input:'hello world'
>>> x
"'hello world'"
>>> eval(x)
'hello world' -
print()用于输出信息到标准控制台或指定文件,语法格式为
print(value1,value2,...,sep='',end=' ',file=sys.stout,flush=False)
-
实例
>>> print(1,2,3,4,5)
1 2 3 4 5
>>> print(1,2,3,4,5,sep=' ')
1 2 3 4 5
>>> print(1,2,3,4,5,sep=' ')
1
2
3
4
5
>>> for i in range(10):
... print(i)
...
0
1
2
3
4
5
6
7
8
9
>>> for i in range(10):
... print(i,end=' ')
...
0 1 2 3 4 5 6 7 8 9 >>>
>>>
>>> with open('test.txt','a+') as fp:
... print('Hello world!',file=fp) # 重定向,将内容输出到文件中
...
>>> -
Python标准库sys还提供了read()和readline()方法用来从键盘接收指定数量的字符
>>> import sys
>>> x = sys.stdin.read(5) # 读取5个字符,如果不足5个,等待继续输入
asd
s
>>> x
'asd s'
>>> x = sys.stdin.read(5) # 读取5个字符,如果超出5个,截取
abcdefghijklmnop
>>> x
' abcd'
>>> x = sys.stdin.read(5) # 从缓存区内继续读取5个字符
>>> x
'efghi'
>>> x = sys.stdin.read(5) # 从缓存区内继续读取5个字符
>>> x
'jklmn'
>>> x = sys.stdin.read(5) # 缓冲区内不足5个字符,就等待用户继续输入
1234
>>> x
'op 12'
>>> x = sys.stdin.readline() # 从缓冲区内读取字符,遇到换行符就结束
>>> x
'34 '
>>> x = sys.stdin.readline()
abcd
>>> x
'abcd '
>>> x = sys.stdin.readline(13) # 如果缓冲区的内容比需要的少,遇到换行符也结束
abcdefg
>>> x
'abcdefg '
>>> x = sys.stdin.readline(13) # 如果缓冲区的内容比需要的多,就截断
abcdefghijklmnopqrst
>>> x
'abcdefghijklm'
>>> x = sys.stdin.readline(13)
>>> x
'nopqrst '