http://blog.csdn.net/pipisorry/article/details/24143801

Python基本输入输出教程

python内置输入函数

python2输入

raw_input()

python3输入

先在交互式解释器中查看input函数
input(...)  
    input([prompt]) -> string 
    Read a string from standard input.  The trailing newline is stripped.  
    If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.  On Unix, GNU readline is used if enabled.  The prompt string, if given,  is printed without a trailing newline before reading. 
笔者的Python是3.3的,根据上面的描述可以很清楚的看到,input函数是从标准输入流读取一个字符串,注意换行符是被剥离的。input可以有一个参数prompt,用来提示输入信息的,下面具体name = input("your name is:")  。If the prompt argument is present, it is written to standard output without a trailing newline.  The function then reads a line from input, converts it to a string.

命令行参数读取

$ python test.py arg1 arg2 arg3

Python 中也可以所用 sys 的 sys.argv 来获取命令行参数:

  • sys.argv 是命令行参数列表。

  • len(sys.argv) 是命令行参数个数。

注:sys.argv[0] 表示脚本名。

sys.stdin.readline()

sys.stdin是一个可读的文件对象,sys.stdout是一个可写的文件对象
sys.stdin与可读文件对象具有相同的类型,sys.stdout与可写文件对象具有相同的类型
StringIO:将字符串当做文件来进行处理

sys.stdin.read()和python2 raw_input()的区别联系

sys.stdin.read()和raw_input()接受和返回的都是原始字符串

sys.stdin.readline() is the fastest one when reading strings and input() when reading integers.lz测试了一下,sys.stdin.readline()无论读取数字还是字符串总是比raw_input()快,不知为何。[sys.stdin.readline() and input(): which one is faster when reading lines of input, and why?]
    区别是raw_input()遇到输入enter停止输入
    sys.stdin.read()读取数据 ctrl+d是结束输入 ,read并不会像input那样遇到回车就返回读取的数据它会缓存或者 等到ctrl d再读取数据
    sys.stdin.readline( )会将标准输入全部获取,包括末尾的'\n',因此用len计算长度时是把换行符'\n'算进去了的,
    但是raw_input( )获取输入时返回的结果是不包含末尾的换行符'\n'的

import sys, os, ioCWD = os.path.split(os.path.realpath(__file__))[0]
sys.path.append(os.path.join(CWD, '..'))
from Oth.Utility.TimeStump import time_blockN = 100000
sys.stdin = io.StringIO(u'''223
334
133
24
34
''' * N)with time_block('1'):while True:a = sys.stdin.readline().strip()if not a:break# with time_block('2'):
#     for i in range(N * 5):
#         a = raw_input()

python使用字符串构建stdin对象

[操作系统服务:其它模块: io模块]
皮皮Blog

python内置输出函数

1. print()函数

Python2.7中是有print语句和内置print函数的,而在Python3.3中,已经没有print语句了,只有print函数,而其实以前的print语句的功能就是print函数默认形式的功能,所以我们在这里就只看看Python3.3中的内置函数print()。

函数原型

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

flush=False是Python3.3加上去的参数。

objects中每一个对象都会被转化为string的形式,然后写到file指定的文件中,默认是标准输出(sys.stdout),每一个对象之间用sep分隔,默认是空格;所有对象都写到文件后,会写入end,默认是换行。

sep和end参数

1 from __future__ import print_function   #Python2.7中使用print()函数,Python3.2中这行代码就不需要了
2 d = {1:'a', 2:'b'}
3 t = (4, 5, 6)
4 l = ['love', 'happiness']
5 print(d, t, l, sep='~', end='^_^\n')

{1: 'a', 2: 'b'}~(4, 5, 6)~['love', 'happiness']^_^

我们已经知道d,t,l会被打包成一个tuple,赋给objects。

应用例子

打印数字1到100,3的倍数打印“Fizz”来替换这个数,5的倍数打印“Buzz”,对于既是3的倍数又是5的倍数的数字打印“FizzBuzz”。
for x in range(101):
    print("fizz"[x%3*4::]+"buzz"[x%5*4::] or x)

Note:

1. x不是3位数时,fizz切片操作为空串''

2. print()函数中or前面为''时才会输出后面的,否则只输出前面的字符
[FizzBuzz编程练习:60个字符解决FizzBuzz - Jeff Atwood]

python输出到stderr中

py2:

print >> sys.stderr, 'string'

[Python标准输出重定向]

py3:

print('string', file=sys.stderr)

命令行中运行python代码重定向即时输出到文件

示例
a.py: 
print('something')
sleep(30)
命令行中执行python3 a.py > log.txt是不能马上在log.txt中看到print输出的。
需要在a.py的print语句后面加上sys.stdout.flush()
[python 文件输出与重定向 ,输出的内容会在内存中暂存,不会立刻输出到文件中]

python输出unicode为中文

python2

print '\u5e94\u8be5'.decode('unicode-escape')

python3

print('\u5e94\u8be5')

结果都是“应该”

print魔法Output caching system

[_] (a single underscore): stores previous output, like Python’sdefault interpreter.

>>> a = 'aaa'
>>> a
'aaa'
>>> print(_)
aaa
在ipython中还另加两个:[__] (two underscores): next previous.[___] (three underscores): next-next previous.

[Output caching system¶]

2.pretty print - pprint()函数

from pprint import pprint   # pretty-printer
>>> pprint(texts)

Note:

1. pprint 模块( pretty printer )用于打印 Python 数据结构. 当你在命令行下打印特定数据结构时你会发现它很有用(输出格式比较整齐, 便于阅读).e.g.会将输出对象列表中的列表元素自动换行输出。

2. pprint模块不能同时打印两个list( pprint(list1, list2) ),否则会出错。

3. json文档打印

如果你想要漂亮的将文件中的json文档打印出来,你可以用以下这种方式:

cat file.json | python -m json.tools

4.格式化输出

打开IDLE输入help(print),我们可以看到如下结果:

[python] view plaincopy

  1. >>> help(print)
  2. Help on built-in function print in module builtins:
  3. print(...)
  4. print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
  5. Prints the values to a stream, or to sys.stdout by default.
  6. Optional keyword arguments:
  7. file:  a file-like object (stream); defaults to the current sys.stdout.
  8. sep:   string inserted between values, default a space.
  9. end:   string appended after the last value, default a newline.
  10. flush: whether to forcibly flush the stream.

从描述中可以看出的是print是支持不定参数的,默认输出到标准输出,而且不清空缓存。各个参数之间默认以空格分隔。输出以一个换行符结束。
1、输出整数。

[python] view plaincopy

  1. >>> print("the length of (%s) is %d" %('Python',len('python')),end="!")
  2. the length of (Python) is 6!

2、其他进制数。
                                 各个进制数的占位符形式:
                                  %x--- hex 十六进制
                                  %d---dec 十进制
                                  %o---oct   八进制

[python] view plaincopy

  1. >>> number=15
  2. >>> print("dec-十进制=%d\noct-八进制=%o\nhex-十六进制=%x" % (number,number,number))
  3. dec-十进制=15
  4. oct-八进制=17
  5. hex-十六进制=f

3、输出字符串

[python] view plaincopy

  1. >>> print ("%.4s " % ("hello world"))
  2. hell

cop

  1. >>> print("%5.4s" %("Hello world"))
  2. Hell

这里输出结果为“ Hello”,前面有一个空格
                            同样对其具体的输出格式也可以写成如下的形式,上面的两个整数可以利用*,来动态代入:

[python] view plaincopy

  1. >>> print("%*.*s" %(5,4,"Hello world"))
  2. Hell

这里对Python的print字符串格式输出形式
                                     %A.Bs:A表示输出的总的字符串长度
                                     B表示要输出字符串从开始截取的长度
                                     A<B的时候,输出字符串长度为B(A可以<0 )
                                     A>B的时候前方空格
                                     B>字符串长度时,后面不用空格占位

4、输出浮点数(float)

[python] view plaincopy

  1. >>> print("%10.3f" % 3.141516)
  2. 3.142

浮点数的输出控制和字符串相似,不过序注意的是.3表示的输出3位小数,最后一面按四舍五入方式进位。

python列表及字典格式化输出

列表及字典输出时,如果元素中存在转义字符\(如\t),则\输出时会自动重复(\\t)。

还有py2的中文输出问题[python中文字符转义问题]

[numpy输入输出]

新式类格式化format输出和扩展形式

[python字符串、字符串处理函数及字符串相关操作 ]

[Python字符串格式化输出详细及其扩展形式]

[python中的字符串对齐输出的另一种实现方式]

str()和repr() - 把object转化为str的形式输出

在Python中,字符串(strings)是由内置类str代表的,这是一个类。同时Python还有内置函数str()。

输入输出都是以字符串的形式,print()就是把非str的object转化为其str的形式输出。那么Python怎么把一个object转化为str的形式呢,Python会把这个object传给内置str()函数。

str()回去寻找这个对象的__str__()属性,如果这个对象没有__str__()属性,str()会调用repr()来得到结果。

class wy:  
    def __str__(self):  
        return "abc"  
  
w = wy()  
print(w)

输出:abc

Note:

1. 如果没有定义__str__(),则会调用repr(wy),会输出:

<__main__.wy2 instance at 0x7f900d0c8050>

2. python2中则是__unicode__()函数

from:http://blog.csdn.net/pipisorry/article/details/39231949

ref:Python输入输出(IO)
Python起步之print & input用法总结

Python输入输出详解相关推荐

  1. python区块链开发_Fabric区块链Python开发详解

    Hyperledger Fabric是最流行的联盟区块链平台.Fabric区块链Python开发详解课程 涵盖Fabric区块链的核心概念.Fabric网络搭建.Node链码开发.Python应用开发 ...

  2. python装饰器setter_第7.27节 Python案例详解: @property装饰器定义属性访问方法getter、setter、deleter...

    上节详细介绍了利用@property装饰器定义属性的语法,本节通过具体案例来进一步说明. 一.    案例说明 本节的案例是定义Rectangle(长方形)类,为了说明问题,除构造函数外,其他方法都只 ...

  3. 【python】详解类class的继承、__init__初始化、super方法

    原文链接; https://blog.csdn.net/brucewong0516/article/details/79121179?utm_medium=distribute.pc_relevant ...

  4. python与golang_Golang与python线程详解及简单实例

    Golang与python线程详解及简单实例 在GO中,开启15个线程,每个线程把全局变量遍历增加100000次,因此预测结果是 15*100000=1500000. var sum int var ...

  5. python 最小二乘法_最小二乘法及其python实现详解

    最小二乘法Least Square Method,做为分类回归算法的基础,有着悠久的历史(由马里·勒让德于1806年提出).它通过最小化误差的平方和寻找数据的最佳函数匹配.利用最小二乘法可以简便地求得 ...

  6. 【python】详解multiprocessing多进程-Pool进程池模块(二)

    [python]详解multiprocessing多进程-process模块(一) [python]详解multiprocessing多进程-Pool进程池模块(二) [python]详解multip ...

  7. 【python】什么是序列,Python序列详解

    什么是序列,Python序列详解 概述 序列索引 序列切片 序列相加 序列相乘 检查元素是否包含在序列中 序列相关的内置函数 range 快速初始化数字列表 概述 所谓序列,指的是一块可存放多个值的连 ...

  8. python多线程详解 Python 垃圾回收机制

    文章目录 python多线程详解 一.线程介绍 什么是线程 为什么要使用多线程 总结起来,使用多线程编程具有如下几个优点: 二.线程实现 自定义线程 守护线程 主线程等待子线程结束 多线程共享全局变量 ...

  9. Python线程详解

    Python线程详解 线程简介 开启多线程 线程之间共享 GIL全局解释器锁 线程间通信 线程简介 线程,有时被称为轻量进程(Lightweight Process,LWP),是程序执行流的最小单元. ...

  10. 07 Python数据类型详解

    文章目录 一.整数类型(int)详解 1.1 整数的不同进制 1) 十进制形式 2) 二进制形式 3) 八进制形式 4) 十六进制形式 1.2 数字分隔符 1.3 相关方法 二.字符串类型(strin ...

最新文章

  1. JS原始类型:数值的运用技巧
  2. Autodesk布道GIS新理念
  3. 程序员面试题精选100题(17)-把字符串转换成整数[算法]
  4. java 重写paint_java笔记 重写paintComponent方法以实现jPanel加背景
  5. 类中匿名函数如何从 event 中去除
  6. javascript笔记:javascript的前世,至于今生嘛地球人都知道了哈
  7. 解决CentOS7 无法启动mysql 的解决办法
  8. 项目管理学习总结(3)——产品文档的规划化管理总结
  9. javascript的阻止默认事件和阻止冒泡事件
  10. 算法 Tricks(一)—— 字符串和数组的翻转
  11. 使用C#如何写入/读取注册表信息
  12. HashMap,LinkedHashMap和Hashtable类的深入剖析与理解
  13. kafka 0.8.2版本配置选项翻译
  14. 谈一下对计算机网络技术的认识,浅谈对计算机网络的认识
  15. 招聘后台投递设置联动按钮迭代开发总结
  16. 影视双端360版2.0带三级分销
  17. 西门子逻辑运算指令_西门子plc 算术、逻辑运算指令
  18. C#应用案例之打字母游戏
  19. MySQL——我的学习笔记
  20. Kinect for Windows SDK 1.6的改进及新特性

热门文章

  1. Android开发中图表的使用
  2. 物理数据库设计 - 读书笔记
  3. 18、Windows API 图形用户界面(2)
  4. MOSS Search学习记录(八):高级搜索定制(中)
  5. 喜欢使用VMware的.net程序员要注意呀(Visual Studio启动不了的问题)
  6. String基本操作
  7. 11月17日站立会议内容
  8. 关于go语言的测试相关内容笔记
  9. maven项目转换成dynamic项目
  10. Action的mapping.findFoward(forwardName)必须要在struts-config.xml中的对应的action节点配置一个forward节点...