Python输入输出详解

来源:互联网 发布:淘宝主图视频拍摄技巧 编辑:程序博客网 时间:2024/06/01 07:33

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

Python基本输入输出教程

python内置输入函数

先在交互式解释器中查看input函数的具体情况。
[python] view plaincopy
  1. input(...)  
  2.     input([prompt]) -> string  
  3.       
  4.     Read a string from standard input.  The trailing newline is stripped.  
  5.     If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.  
  6.     On Unix, GNU readline is used if enabled.  The prompt string, if given,  
  7.     is printed without a trailing newline before reading.  
  8.   
  9. >>>   
 注意这里笔者的Python是3.3的,根据上面的描述可以很清楚的看到,input函数是从标准输入流
读取一个字符串,注意换行符是被剥离的。input可以有一个参数,用来提示输入信息的,下面具体
例子:
[python] view plaincopy
  1. >>> name = input("your name is:")  
  2. your name is:kiritor  
  3. >>> print(name)  
  4. kiritor  
  5. >>>   
查看官方文档我们可以更清楚的明白input是如何工作的。                
[python] view plaincopy
  1. If the prompt argument is present, it is written to standard output without a trailing newline.  
  2.  The function then reads a line from input, converts it to a string

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]

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.   
  4. print(...)  
  5.     print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)  
  6.       
  7.     Prints the values to a stream, or to sys.stdout by default.  
  8.     Optional keyword arguments:  
  9.     file:  a file-like object (stream); defaults to the current sys.stdout.  
  10.     sep:   string inserted between values, default a space.  
  11.     end:   string appended after the last value, default a newline.  
  12.     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列表格式化输出

[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用法总结


1 0
原创粉丝点击