Python基础06 标准输入和输出

标准输入输出


sys.stdin.readline() 与 raw_input()

import sys

a = sys.stdin.readline().strip('\n')

值得注意的是,sys.stdin.readline()会把标准输入全部获取,包括末尾的换行符 '\n',我们用 strip('\n') 去掉换行符 '\n' 就可以了。

当我们用内置函数 raw_input() 时,事实上是先把提示信息输出,然后获取输入:

#coding=utf8

a = raw_input('请输入:')

与 sys.stdin.readline() 一样,raw_input() 将所有输入作为字符串看待,返回字符串类型。input() 接收字符串必须带引号(Python 2.7版本),接收的整形或浮点型数据,返回的也是整形或浮点型。

复制代码
#coding=utf8
name = raw_input('输入姓名:')
age = raw_input('输入年龄:')

print name, type(name)
print age, type(age)

a = input('输入姓名:')
b = input('输入年龄:')

print a, type(a)
print b, type(b)


输入姓名:聂离
输入年龄:13
聂离 <type 'str'>
13 <type 'str'>
输入姓名:'聂离'
输入年龄:13
聂离 <type 'str'>
13 <type 'int'>
复制代码

sys.stdout 与 print

当我们在 Python 中打印对象调用 print obj 时候,事实上是调用了 sys.stdout.write(obj+'\n')。

print 将你需要的内容打印到控制台,然后追加了一个换行符。

import sys
sys.stdout.write('hello'+'\n')

print('hello')

猜你喜欢

转载自www.cnblogs.com/yutb/p/10782982.html