Python学习总结【第01篇】:Python简介及入门
Python简介
Python介绍
Python的创始人:Guido van Rossum
最新的TIOBE排行榜:http://www.tiobe.com/tiobe_index
Python官网:https://www.python.org/
Python下载:https://www.python.org/downloads/
学习建议:安装Python 2.7.1和Python 3.5.1两个版本
Python应用
Python可以应用于众多领域,如:数据分析、组件集成、网络服务、图像处理、数值计算和科学计算等众多领域。目前业内几乎所有大中型互联网企业都在使用Python,如:Youtube、Dropbox、BT、Quora(中国知乎)、豆瓣、知乎、Google、Yahoo!、Facebook、NASA、百度、腾讯、汽车之家、美团等。
目前Python主要应用领域:
1)、云计算: 云计算最火的语言, 典型应用OpenStack
2)、WEB开发: 众多优秀的WEB框架,众多大型网站均为Python开发,Youtube, Dropbox, 豆瓣。。。, 典型WEB框架有Django
3)、科学运算、人工智能: 典型库NumPy, SciPy, Matplotlib, Enthought librarys,pandas
4)、系统运维: 运维人员必备语言
5)、金融:量化交易,金融分析,在金融工程领域,Python不但在用,且用的最多,而且重要性逐年提高。原因:作为动态语言的Python,语言结构清晰简单,库丰富,成熟稳定,科学计算和统计分析都很牛逼,生产效率远远高于c,c++,java,尤其擅长策略回测
6)、图形GUI: PyQT, WxPython,TkInter
Python在一些公司的应用:
谷歌:Google App Engine 、code.google.com 、Google earth 、谷歌爬虫、Google广告等项目都在大量使用Python开发
CIA: 美国中情局网站就是用Python开发的
NASA: 美国航天局(NASA)大量使用Python进行数据分析和运算
YouTube:世界上最大的视频网站YouTube就是用Python开发的
Dropbox:美国最大的在线云存储网站,全部用Python实现,每天网站处理10亿个文件的上传和下载
Instagram:美国最大的图片分享社交网站,每天超过3千万张照片被分享,全部用python开发
Facebook:大量的基础库均通过Python实现的
Redhat: 世界上最流行的Linux发行版本中的yum包管理工具就是用python开发的
豆瓣: 公司几乎所有的业务均是通过Python开发的
知乎: 国内最大的问答社区,通过Python开发(国外Quora)
春雨医生:国内知名的在线医疗网站是用Python开发的
除上面之外,还有搜狐、金山、腾讯、盛大、网易、百度、阿里、淘宝 、土豆、新浪、果壳等公司都在使用Python完成各种各样的任务。
Python解释器
1)Cpython(官方)
当我们从Python官方网站下载并安装好Python 2.7后,我们就直接获得了一个官方版本的解释器:CPython。这个解释器是用C语言开发的,所以叫CPython。在命令行下运行python就是启动CPython解释器。CPython是使用最广的Python解释器。
2)IPython
IPython是基于CPython之上的一个交互式解释器,也就是说,IPython只是在交互方式上有所增强,但是执行Python代码的功能和CPython是完全一样的。好比很多国产浏览器虽然外观不同,但内核其实都是调用了IE。
CPython用>>>作为提示符,而IPython用In [序号]:作为提示符。
3)PyPy
PyPy是另一个Python解释器,它的目标是执行速度。PyPy采用JIT技术,对Python代码进行动态编译(注意不是解释),所以可以显著提高Python代码的执行速度。绝大部分Python代码都可以在PyPy下运行,但是PyPy和CPython有一些是不同的,这就导致相同的Python代码在两种解释器下执行可能会有不同的结果。如果你的代码要放到PyPy下执行,就需要了解PyPy和CPython的不同点。
4)Jython
Jython是运行在Java平台上的Python解释器,可以直接把Python代码编译成Java字节码执行。
5)IronPython
IronPython和Jython类似,只不过IronPython是运行在微软.Net平台上的Python解释器,可以直接把Python代码编译成.Net的字节码。
小结:
Python的解释器很多,但使用最广泛的还是CPython。如果要和Java或.Net平台交互,最好的办法不是用Jython或IronPython,而是通过网络调用来交互,确保各程序之间的独立性。
Python Web框架
Django
Django 应该是最出名的Python框架,GAE甚至Erlang都有框架受它影响。Django是走大而全的方向,它最出名的是其全自动化的管理后台:只需要使用起ORM,做简单的对象定义,它就能自动生成数据库结构、以及全功能的管理后台。
Flask
Flask是一个使用Python编写的轻量级Web应用框架。基于Werkzeug WSGI工具箱和Jinja2 模板引擎。Flask也被称为“microframework”,因为它使用简单的核心,用extension增加其他功能。Flask没有默认使用的数据库、窗体验证工具。
Web2py
Web2py是一个为Python语言提供的全功能Web应用框架,旨在敏捷快速的开发Web应用,具有快速、安全以及可移植的数据库驱动的应用,兼容Google App Engine。
Tornado
Tornado的全称是Torado Web Server,从名字上看就可知道它可以用作Web服务器,但同时它也是一个Python Web的开发框架。最初是在FriendFeed公司的网站上使用,FaceBook收购了之后便开源了出来。
文档: http://www.tornadoweb.cn/
http://www.tornadoweb.org/en/stable/
http://demo.pythoner.com/itt2zh/index.html
Uliweb
国人开发的轻量级web开发框架 Pylons
Python设计及定位
# python -c "import this" The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those! Python的禅宗,蒂姆•彼得斯 美丽优于丑陋。 显式优于隐式。 简单优于复杂。 复杂的比复杂。 平比嵌套。 稀疏的密度比。 可读性很重要。 特殊情况不是特别足以打破规则。 尽管实用性比纯洁。 错误不应该通过默默地。 除非显式地沉默。 面对歧义,拒绝猜测的诱惑。 应该有一个,最好是只有一个——明显的方式去做。 虽然这样可能没有明显的起初,除非你是荷兰人。 现在是更好的比不做好。 虽然不常比* *现在。 如果实现很难解释,这是一个糟糕的主意。 如果实现很容易解释,这可能是一个好主意。 名称空间是一个很棒的想法——让我们做更多的!
Python发展历史
1989年,为了打发圣诞节假期,Guido开始写Python语言的编译器。Python这个名字,来自Guido所挚爱的电视剧Monty Python’s Flying Circus。他希望这个新的叫做Python的语言,能符合他的理想:创造一种C和shell之间,功能全面,易学易用,可拓展的语言。
1991年,第一个Python编译器诞生。它是用C语言实现的,并能够调用C语言的库文件。从一出生,Python已经具有了:类,函数,异常处理,包含表和词典在内的核心数据类型,以及模块为基础的拓展系统。
Granddaddy of Python web frameworks, Zope 1 was released in 1999
Python 1.0 - January 1994 增加了 lambda, map, filter and reduce.
Python 2.0 - October 16, 2000,加入了内存回收机制,构成了现在Python语言框架的基础
Python 2.4 - November 30, 2004, 同年目前最流行的WEB框架Django 诞生
Python 2.5 - September 19, 2006
Python 2.6 - October 1, 2008
Python 2.7 - July 3, 2010
In November 2014, it was announced that Python 2.7 would be supported until 2020, and reaffirmed that there would be no 2.8 release as users were expected to move to Python 3.4+ as soon as possible
Python 3.0 - December 3, 2008
Python 3.1 - June 27, 2009
Python 3.2 - February 20, 2011
Python 3.3 - September 29, 2012
Python 3.4 - March 16, 2014
Python 3.5 - September 13, 2015
Python2.x和Python 3.x对比
1 概述
Python 2.7 是一个过渡版本
Python 3.x 是长期版本
2 详细差异
1)编码问题 Python3.x无需再特意指定UTF-8,默认支持UTF-8编码
2)print函数区别
C:\Users\Administrator>python Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:32:19) [MSC v.1500 32 bit ( Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> print "Hello World" Hello World >>> C:\Users\Administrator>python3 Python 3.5.0 (v3.5.0:374f501f4567, Sep 13 2015, 02:16:59) [MSC v.1900 32 bit (In tel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> print "Hello World" File "<stdin>", line 1 print "Hello World" ^ SyntaxError: Missing parentheses in call to 'print' >>> print("Hello World") Hello World
3)某些库改名了
4)用户输入
Python 2.x:raw_input
Python 3.x:input
5)1/2问题
C:\Users\Administrator>python Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:32:19) [MSC v.1500 32 bit ( Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> 1/2 0 >>> C:\Users\Administrator>python3 Python 3.5.0 (v3.5.0:374f501f4567, Sep 13 2015, 02:16:59) [MSC v.1900 32 bit (In tel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> 1/2 0.5
6)class定义
7)性能
Py3.0运行 pystone benchmark的速度比Py2.5慢30%。Guido认为Py3.0有极大的优化空间,在字符串和整形操作上可
以取得很好的优化结果。
Py3.1性能比Py2.5慢15%,还有很大的提升空间。
8)range()
Python 2.x >>> range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> type(range(10)) <type 'list'> Python 3.x >>> range(10) range(0, 10) >>> type(range(10)) <class 'range'>
Python安装
安装介绍
1、Python for Windows
1)官网下载对应的Python版本
下载地址:https://www.python.org/downloads/windows/
2)设置环境变量
3)cmd python 测试是否生效
C:\Users\Administrator>python Python2.7.11 (v2.7.11:6d1b6a68f775, Dec 52015, 20:32:19) [MSC v.1500 32 bit ( Intel)]on win32 Type"help", "copyright", "credits" or"license" for more information. >>>exit() # 如何退出
4)可以同时安装多个Python for Windows版本,安装时自定义安装目录,都设置环境变量即可,注意多个版本的程序名称要做修改。例如:Python 2.x默认命名为python,Python 3.x可以命名为python3 保证不互相冲突。
2、Python for Linux
2.1 RPM包安装
常见linux发行版本Python环境都已经默认安装
2.2 源码编译安装
yum install gcc gcc-c++ automake autoconf python-devel wget https://www.python.org/ftp/python/3.4/Python-3.4.3.tgz tar -zxf Python-3.4.3.tgz cd Python-3.4.3 ./configure --enable-shared --prefix=/usr/local/python-3.4.3 make -j8 && make install # 安装pip wget https://bootstrap.pypa.io/get-pip.py python get-pip.py
# 查看当前安装软件包版本
pip freeze
使用建议
Window 下开发工具较多,优先在Windows环境开发
Linux环境适用于代码调试和简单的运维脚本编写
5、第一个Python程序
mads@mads-virtual-machine:~/python$ cat hello.py #!/usr/bin/env python3 # 明确的指出hello.py脚本由python解释器来执行 #_*_coding:utf-8_*_ print("Hello World!") mads@mads-virtual-machine:~/python$ chmod +x hello.py # 执行前需给予hello.py执行权限 mads@mads-virtual-machine:~/python$ ./hello.py Hello World!
对比其他语言hello world
http://madsstudy.blog.51cto.com/6249249/1771215
Python内部执行过程(转)
6、变量
6.1 变量声明
#!/usr/bin/env python # encoding: utf-8 name = "zhangsan" 注:声明了一个变量,变量名为: name,变量name的值为:"zhangsan"
6.2 变量定义规则
1)变量名只能是 字母、数字或下划线的任意组合
2)变量名的第一个字符不能是数字,可以是下划线及字母
3)不能与Python关键字重复
['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del','elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print','raise', 'return', 'try', 'while', 'with', 'yield']
6.3 变量赋值
name1 = "zhangsan"
name2 = name1
print(name1,name2)
print(id(name1),id(name2))
name1 = "lisi"
print(name1,name2)
print(id(name1),id(name2))
解释为何最后name1 与 name2的值不同?
1)给name1变量分配一个内存地址存放name的值zhangsan
2)把name2变量的值等于nam1e内存地址中存放的值zhangsan
3)将name1的变量值修改为lisi,是重新分配一个内存地址存放name1的新值,此时 name1=lisi 而name2不变等于zhangsan
6.4 多个变量同时赋值
>>> name,age = "Alex Li",22 >>> print("your name is %s and age is %d" % (name,age)) your name is Alex Li and age is 22
6.5 常量
常量命名都使用大写字符
7、字符编码
字符编码出现的时间:ASCII>Unicode>UTF-8
三种编码的特点
1)ASCII:(American Standard Code for Information Interchange,美国标准信息交换代码)是基于拉丁字母的一套电脑编码系统,主要用于显示现代英语和其他西欧语言,其最多只能用 8 位来表示(一个字节),即:2**8 = 256-1,所以,ASCII码最多只能表示 255 个符号
2)Unicode:Unicode(统一码、万国码、单一码)是一种在计算机上使用的字符编码。Unicode 是为了解决传统的字符编码方案的局限而产生的,它为每种语言中的每个字符设定了统一并且唯一的二进制编码,规定虽有的字符和符号最少由 16 位来表示(2个字节),即:2 **16 = 65536,注:此处说的的是最少2个字节,可能更多
3)UTF-8:UTF-8,是对Unicode编码的压缩和优化,他不再使用最少使用2个字节,而是将所有的字符和符号进行分类:ascii码中的内容用1个字节保存、欧洲的字符用2个字节保存,东亚的字符用3个字节保存...
Python解释器在加载.py文件中的代码时,会对内容进行编码(默认ASCII),如下报错:
mads@mads-virtual-machine:~/python$ cat hello.py #!/usr/bin/env python print('你好') mads@mads-virtual-machine:~/python$ python hello.py File "hello2.py", line 3 SyntaxError: Non-ASCII character '\xe4' in file hello2.py on line 3, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details
解决:
mads@mads-virtual-machine:~/python$ cat hello.py #!/usr/bin/env python #_*_coding:utf-8_*_ print(u'你好') mads@mads-virtual-machine:~/python$ python hello.py 你好 Python 3.X已经不存在这个问题 mads@mads-virtual-machine:~/python$ cat hello.py #!/usr/bin/env python3 print('你好') mads@mads-virtual-machine:~/python$ python3 hello.py 你好
8、注释
注释原则:源程序有效注释量应该在20%以上,注释的原则是有助于对程序的阅读理解,在该加的地方都加了,注释不宜太多也不能太少,注释语言必须准确、易懂、简洁。
开发规范1:每行不能超过80个字符
单行注释:# 我被注释掉了,仅到行尾为止
多行注释:''' 在这个范围内的所有内容都经被注释'''
9、用户输入
9.1 常规使用
#!/usr/bin/env python3 # encoding: utf-8 name = input("Please input your name:") # Python 3.x name = raw_input("Please input your name:") # Python 2.x print(name)
9.2 隐藏输入内容实现
getpass模块(适用范围 linux可以, PyChram不行; Python 3.x可以)
mads@mads-virtual-machine:~/python$ cat test_getpass.py #!/usr/bin/python #-*-coding:utf-8-*- import getpass username = input("username:") password = getpass.getpass("password:") print (username,password) mads@mads-virtual-machine:~/python$ python3 test_getpass.py username:root password: root sss
10、模块
Python的强大之处在于他有非常丰富和强大的标准库和第三方库,几乎你想实现的任何功能都有相应的Python库支持
sys:
mads@mads-virtual-machine:~/python$ cat input.py #!/usr/bin/env python #_*_coding:utf-8_*_ import sys if len(sys.argv)<2: print "\033[32;1m"+"Usages: Host Port"+"\033[0m" sys.exit(2) host = sys.argv[1] port = sys.argv[2] print "host:%s port:%s" % (host,port) mads@mads-virtual-machine:~/python$ python input.py 192.168.1.1 22 host:192.168.1.1 port:22
os:
>>> import os >>> os.mkdir('student') # 新建目录 >>> os.system('ls -l') # 查看当前目录内容总用量 20 -rwxrwxr-x 1 mads mads 83 5月 8 15:39 hello.py drwxrwxr-x 2 mads mads 4096 5月 8 18:02 __pycache__ drwxrwxr-x 2 mads mads 4096 5月 8 18:16 student -rwxrwxr-x 1 mads mads 151 5月 8 18:00 test_getpass.py -rwxrwxr-x 1 mads mads 73 5月 5 15:53 test.py0 >>> cmd_res = os.system('ls -l') # 仅保存命令执行的返回值总用量 20 -rwxrwxr-x 1 mads mads 83 5月 8 15:39 hello.py drwxrwxr-x 2 mads mads 4096 5月 8 18:02 __pycache__ drwxrwxr-x 2 mads mads 4096 5月 8 18:16 student -rwxrwxr-x 1 mads mads 151 5月 8 18:00 test_getpass.py -rwxrwxr-x 1 mads mads 73 5月 5 15:53 test.py >>> print cmd_res0 >>> cmd_res = os.popen('ls -l').read() # 保存命令的执行结果 >>> print cmd_res 总用量 20 -rwxrwxr-x 1 mads mads 83 5月 8 15:39 hello.py drwxrwxr-x 2 mads mads 4096 5月 8 18:02 __pycache__ drwxrwxr-x 2 mads mads 4096 5月 8 18:16 student -rwxrwxr-x 1 mads mads 151 5月 8 18:00 test_getpass.py -rwxrwxr-x 1 mads mads 73 5月 5 15:53 test.py
sys和os结合
import sys,os os.system(''.join(sys.argv[1:]))
设置各个环境下Python的tab补全功能
1)安装pyreadline模块
2)edit and configure pythonstartup file
windows环境
# python startup file for window import sys import readline import rlcompleter import atexit import os # tab completion readline.parse_and_bind('tab: complete') del os,readline, rlcompleter
linux环境
#!/usr/bin/env python # python startup file import sys import readline import rlcompleter import atexit import os # tab completion readline.parse_and_bind('tab: complete') # history file histfile = os.path.join(os.environ['HOME'], '.pythonhistory') try: readline.read_history_file(histfile) except IOError: pass atexit.register(readline.write_history_file, histfile) del os, histfile, readline, rlcompleter
mac环境
import sys import readline import rlcompleter if sys.platform == 'darwin' and sys.version_info[0] == 2: readline.parse_and_bind("bind ^I rl_complete") else: readline.parse_and_bind("tab: complete") # linux and python3 on mac
3)add the enviroment varable to system with administrator role
For windowns
For Linux
add the following to you ~/.bash_profile
export PYTHONSTARTUP=~/.pythonstartup
注:保存内容为tab.py,使用import tab命令引用该模块。如果想在系统的何何一个地方都使用,要把这个tab.py放到python全局环境变量目录里。print(sys.path) 可以查看python环境变量列表,基本一般都放在一个叫 Python/2.7/site-packages 目录下,这个目录在不同的OS里放的位置不一样。
注意:环境列表的第一个' '表示当前目录,即环境查找的顺序问题
vim环境下这Python的tab补全功能
wget https://github.com/rkulla/pydiction/archive/master.zip unzip -q master mv pydiction-master pydiction mkdir -p ~/.vim/tools/pydiction cp -r pydiction/after ~/.vim cp pydiction/complete-dict ~/.vim/tools/pydiction
11、Python语言
1)编译型和解释型
编译型:首先由编译器编译成机器能识别的机器码,才能开始执行
解释型:一般翻译一遍执行
2)动态类型语言和静态类型语言
动态类型语言:在运行期间才会做数据类型的检查的语言
静态类型语言:在编写程序的时候就要声明所有变量的数据类型
3)强类型定义语言和弱类型定义语言
强类型定义语言:变量一旦被赋值,必须经过强制转换才能被再次使用
弱类型定义语言:与强类型语言相反,一个变量可以附不用数据类型的值
结论:python是一门动态解释性的强类型定义语言
12、数据类型
type函数:查看数据类型
12.1 数字类型(number)
1)整数(int)
class int(object): """ int(x=0) -> int or long int(x, base=10) -> int or long Convert a number or string to an integer, or return 0 if no arguments are given. If x is floating point, the conversion truncates towards zero. If x is outside the integer range, the function returns a long instead. If x is not a number or if base is given, then x must be a string or Unicode object representing an integer literal in the given base. The literal can be preceded by '+' or '-' and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer literal. >>> int('0b100', base=0) """ def bit_length(self): """ 返回表示该数字的时占用的最少位数 """ """ int.bit_length() -> int Number of bits necessary to represent self in binary. >>> bin(37) '0b100101' >>> (37).bit_length() """ return 0 def conjugate(self, *args, **kwargs): # real signature unknown """ 返回该复数的共轭复数 """ """ Returns self, the complex conjugate of any int. """ pass def __abs__(self): """ 返回绝对值 """ """ x.__abs__() <==> abs(x) """ pass def __add__(self, y): """ x.__add__(y) <==> x+y """ pass def __and__(self, y): """ x.__and__(y) <==> x&y """ pass def __cmp__(self, y): """ 比较两个数大小 """ """ x.__cmp__(y) <==> cmp(x,y) """ pass def __coerce__(self, y): """ 强制生成一个元组 """ """ x.__coerce__(y) <==> coerce(x, y) """ pass def __divmod__(self, y): """ 相除,得到商和余数组成的元组 """ """ x.__divmod__(y) <==> divmod(x, y) """ pass def __div__(self, y): """ x.__div__(y) <==> x/y """ pass def __float__(self): """ 转换为浮点类型 """ """ x.__float__() <==> float(x) """ pass def __floordiv__(self, y): """ x.__floordiv__(y) <==> x//y """ pass def __format__(self, *args, **kwargs): # real signature unknown pass def __getattribute__(self, name): """ x.__getattribute__('name') <==> x.name """ pass def __getnewargs__(self, *args, **kwargs): # real signature unknown """ 内部调用 __new__方法或创建对象时传入参数使用 """ pass def __hash__(self): """如果对象object为哈希表类型,返回对象object的哈希值。哈希值为整数。在字典查找中,哈希值用于快速比较字典的键。两个数值如果相等,则哈希值也相等。""" """ x.__hash__() <==> hash(x) """ pass def __hex__(self): """ 返回当前数的 十六进制 表示 """ """ x.__hex__() <==> hex(x) """ pass def __index__(self): """ 用于切片,数字无意义 """ """ x[y:z] <==> x[y.__index__():z.__index__()] """ pass def __init__(self, x, base=10): # known special case of int.__init__ """ 构造方法,执行 x = 123 或 x = int(10) 时,自动调用,暂时忽略 """ """ int(x=0) -> int or long int(x, base=10) -> int or long Convert a number or string to an integer, or return 0 if no arguments are given. If x is floating point, the conversion truncates towards zero. If x is outside the integer range, the function returns a long instead. If x is not a number or if base is given, then x must be a string or Unicode object representing an integer literal in the given base. The literal can be preceded by '+' or '-' and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer literal. >>> int('0b100', base=0) # (copied from class doc) """ pass def __int__(self): """ 转换为整数 """ """ x.__int__() <==> int(x) """ pass def __invert__(self): """ x.__invert__() <==> ~x """ pass def __long__(self): """ 转换为长整数 """ """ x.__long__() <==> long(x) """ pass def __lshift__(self, y): """ x.__lshift__(y) <==> x<<y """ pass def __mod__(self, y): """ x.__mod__(y) <==> x%y """ pass def __mul__(self, y): """ x.__mul__(y) <==> x*y """ pass def __neg__(self): """ x.__neg__() <==> -x """ pass @staticmethod # known case of __new__ def __new__(S, *more): """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass def __nonzero__(self): """ x.__nonzero__() <==> x != 0 """ pass def __oct__(self): """ 返回改值的 八进制 表示 """ """ x.__oct__() <==> oct(x) """ pass def __or__(self, y): """ x.__or__(y) <==> x|y """ pass def __pos__(self): """ x.__pos__() <==> +x """ pass def __pow__(self, y, z=None): """ 幂,次方 """ """ x.__pow__(y[, z]) <==> pow(x, y[, z]) """ pass def __radd__(self, y): """ x.__radd__(y) <==> y+x """ pass def __rand__(self, y): """ x.__rand__(y) <==> y&x """ pass def __rdivmod__(self, y): """ x.__rdivmod__(y) <==> divmod(y, x) """ pass def __rdiv__(self, y): """ x.__rdiv__(y) <==> y/x """ pass def __repr__(self): """转化为解释器可读取的形式 """ """ x.__repr__() <==> repr(x) """ pass def __str__(self): """转换为人阅读的形式,如果没有适于人阅读的解释形式的话,则返回解释器课阅读的形式""" """ x.__str__() <==> str(x) """ pass def __rfloordiv__(self, y): """ x.__rfloordiv__(y) <==> y//x """ pass def __rlshift__(self, y): """ x.__rlshift__(y) <==> y<<x """ pass def __rmod__(self, y): """ x.__rmod__(y) <==> y%x """ pass def __rmul__(self, y): """ x.__rmul__(y) <==> y*x """ pass def __ror__(self, y): """ x.__ror__(y) <==> y|x """ pass def __rpow__(self, x, z=None): """ y.__rpow__(x[, z]) <==> pow(x, y[, z]) """ pass def __rrshift__(self, y): """ x.__rrshift__(y) <==> y>>x """ pass def __rshift__(self, y): """ x.__rshift__(y) <==> x>>y """ pass def __rsub__(self, y): """ x.__rsub__(y) <==> y-x """ pass def __rtruediv__(self, y): """ x.__rtruediv__(y) <==> y/x """ pass def __rxor__(self, y): """ x.__rxor__(y) <==> y^x """ pass def __sub__(self, y): """ x.__sub__(y) <==> x-y """ pass def __truediv__(self, y): """ x.__truediv__(y) <==> x/y """ pass def __trunc__(self, *args, **kwargs): """ 返回数值被截取为整形的值,在整形中无意义 """ pass def __xor__(self, y): """ x.__xor__(y) <==> x^y """ pass denominator = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """ 分母 = 1 """ """the denominator of a rational number in lowest terms""" imag = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """ 虚数,无意义 """ """the imaginary part of a complex number""" numerator = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """ 分子 = 数字大小 """ """the numerator of a rational number in lowest terms""" real = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """ 实属,无意义 """ """the real part of a complex number""" int
2)长整型(long)(Python 3.x 已经不用了)
class long(object): """ long(x=0) -> long long(x, base=10) -> long Convert a number or string to a long integer, or return 0L if no arguments are given. If x is floating point, the conversion truncates towards zero. If x is not a number or if base is given, then x must be a string or Unicode object representing an integer literal in the given base. The literal can be preceded by '+' or '-' and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer literal. >>> int('0b100', base=0) 4L """ def bit_length(self): # real signature unknown; restored from __doc__ """ long.bit_length() -> int or long Number of bits necessary to represent self in binary. >>> bin(37L) '0b100101' >>> (37L).bit_length() """ return 0 def conjugate(self, *args, **kwargs): # real signature unknown """ Returns self, the complex conjugate of any long. """ pass def __abs__(self): # real signature unknown; restored from __doc__ """ x.__abs__() <==> abs(x) """ pass def __add__(self, y): # real signature unknown; restored from __doc__ """ x.__add__(y) <==> x+y """ pass def __and__(self, y): # real signature unknown; restored from __doc__ """ x.__and__(y) <==> x&y """ pass def __cmp__(self, y): # real signature unknown; restored from __doc__ """ x.__cmp__(y) <==> cmp(x,y) """ pass def __coerce__(self, y): # real signature unknown; restored from __doc__ """ x.__coerce__(y) <==> coerce(x, y) """ pass def __divmod__(self, y): # real signature unknown; restored from __doc__ """ x.__divmod__(y) <==> divmod(x, y) """ pass def __div__(self, y): # real signature unknown; restored from __doc__ """ x.__div__(y) <==> x/y """ pass def __float__(self): # real signature unknown; restored from __doc__ """ x.__float__() <==> float(x) """ pass def __floordiv__(self, y): # real signature unknown; restored from __doc__ """ x.__floordiv__(y) <==> x//y """ pass def __format__(self, *args, **kwargs): # real signature unknown pass def __getattribute__(self, name): # real signature unknown; restored from __doc__ """ x.__getattribute__('name') <==> x.name """ pass def __getnewargs__(self, *args, **kwargs): # real signature unknown pass def __hash__(self): # real signature unknown; restored from __doc__ """ x.__hash__() <==> hash(x) """ pass def __hex__(self): # real signature unknown; restored from __doc__ """ x.__hex__() <==> hex(x) """ pass def __index__(self): # real signature unknown; restored from __doc__ """ x[y:z] <==> x[y.__index__():z.__index__()] """ pass def __init__(self, x=0): # real signature unknown; restored from __doc__ pass def __int__(self): # real signature unknown; restored from __doc__ """ x.__int__() <==> int(x) """ pass def __invert__(self): # real signature unknown; restored from __doc__ """ x.__invert__() <==> ~x """ pass def __long__(self): # real signature unknown; restored from __doc__ """ x.__long__() <==> long(x) """ pass def __lshift__(self, y): # real signature unknown; restored from __doc__ """ x.__lshift__(y) <==> x<<y """ pass def __mod__(self, y): # real signature unknown; restored from __doc__ """ x.__mod__(y) <==> x%y """ pass def __mul__(self, y): # real signature unknown; restored from __doc__ """ x.__mul__(y) <==> x*y """ pass def __neg__(self): # real signature unknown; restored from __doc__ """ x.__neg__() <==> -x """ pass @staticmethod # known case of __new__ def __new__(S, *more): # real signature unknown; restored from __doc__ """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass def __nonzero__(self): # real signature unknown; restored from __doc__ """ x.__nonzero__() <==> x != 0 """ pass def __oct__(self): # real signature unknown; restored from __doc__ """ x.__oct__() <==> oct(x) """ pass def __or__(self, y): # real signature unknown; restored from __doc__ """ x.__or__(y) <==> x|y """ pass def __pos__(self): # real signature unknown; restored from __doc__ """ x.__pos__() <==> +x """ pass def __pow__(self, y, z=None): # real signature unknown; restored from __doc__ """ x.__pow__(y[, z]) <==> pow(x, y[, z]) """ pass def __radd__(self, y): # real signature unknown; restored from __doc__ """ x.__radd__(y) <==> y+x """ pass def __rand__(self, y): # real signature unknown; restored from __doc__ """ x.__rand__(y) <==> y&x """ pass def __rdivmod__(self, y): # real signature unknown; restored from __doc__ """ x.__rdivmod__(y) <==> divmod(y, x) """ pass def __rdiv__(self, y): # real signature unknown; restored from __doc__ """ x.__rdiv__(y) <==> y/x """ pass def __repr__(self): # real signature unknown; restored from __doc__ """ x.__repr__() <==> repr(x) """ pass def __rfloordiv__(self, y): # real signature unknown; restored from __doc__ """ x.__rfloordiv__(y) <==> y//x """ pass def __rlshift__(self, y): # real signature unknown; restored from __doc__ """ x.__rlshift__(y) <==> y<<x """ pass def __rmod__(self, y): # real signature unknown; restored from __doc__ """ x.__rmod__(y) <==> y%x """ pass def __rmul__(self, y): # real signature unknown; restored from __doc__ """ x.__rmul__(y) <==> y*x """ pass def __ror__(self, y): # real signature unknown; restored from __doc__ """ x.__ror__(y) <==> y|x """ pass def __rpow__(self, x, z=None): # real signature unknown; restored from __doc__ """ y.__rpow__(x[, z]) <==> pow(x, y[, z]) """ pass def __rrshift__(self, y): # real signature unknown; restored from __doc__ """ x.__rrshift__(y) <==> y>>x """ pass def __rshift__(self, y): # real signature unknown; restored from __doc__ """ x.__rshift__(y) <==> x>>y """ pass def __rsub__(self, y): # real signature unknown; restored from __doc__ """ x.__rsub__(y) <==> y-x """ pass def __rtruediv__(self, y): # real signature unknown; restored from __doc__ """ x.__rtruediv__(y) <==> y/x """ pass def __rxor__(self, y): # real signature unknown; restored from __doc__ """ x.__rxor__(y) <==> y^x """ pass def __sizeof__(self, *args, **kwargs): # real signature unknown """ Returns size in memory, in bytes """ pass def __str__(self): # real signature unknown; restored from __doc__ """ x.__str__() <==> str(x) """ pass def __sub__(self, y): # real signature unknown; restored from __doc__ """ x.__sub__(y) <==> x-y """ pass def __truediv__(self, y): # real signature unknown; restored from __doc__ """ x.__truediv__(y) <==> x/y """ pass def __trunc__(self, *args, **kwargs): # real signature unknown """ Truncating an Integral returns itself. """ pass def __xor__(self, y): # real signature unknown; restored from __doc__ """ x.__xor__(y) <==> x^y """ pass denominator = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """the denominator of a rational number in lowest terms""" imag = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """the imaginary part of a complex number""" numerator = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """the numerator of a rational number in lowest terms""" real = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """the real part of a complex number""" long
3)浮点型(float)
class float(object): """ float(x) -> floating point number Convert a string or number to a floating point number, if possible. """ def as_integer_ratio(self): """ 获取改值的最简比 """ """ float.as_integer_ratio() -> (int, int) Return a pair of integers, whose ratio is exactly equal to the original float and with a positive denominator. Raise OverflowError on infinities and a ValueError on NaNs. >>> (10.0).as_integer_ratio() (10, 1) >>> (0.0).as_integer_ratio() (0, 1) >>> (-.25).as_integer_ratio() (-1, 4) """ pass def conjugate(self, *args, **kwargs): # real signature unknown """ Return self, the complex conjugate of any float. """ pass def fromhex(self, string): """ 将十六进制字符串转换成浮点型 """ """ float.fromhex(string) -> float Create a floating-point number from a hexadecimal string. >>> float.fromhex('0x1.ffffp10') 2047.984375 >>> float.fromhex('-0x1p-1074') -4.9406564584124654e-324 """ return 0.0 def hex(self): """ 返回当前值的 16 进制表示 """ """ float.hex() -> string Return a hexadecimal representation of a floating-point number. >>> (-0.1).hex() '-0x1.999999999999ap-4' >>> 3.14159.hex() '0x1.921f9f01b866ep+1' """ return "" def is_integer(self, *args, **kwargs): # real signature unknown """ Return True if the float is an integer. """ pass def __abs__(self): """ x.__abs__() <==> abs(x) """ pass def __add__(self, y): """ x.__add__(y) <==> x+y """ pass def __coerce__(self, y): """ x.__coerce__(y) <==> coerce(x, y) """ pass def __divmod__(self, y): """ x.__divmod__(y) <==> divmod(x, y) """ pass def __div__(self, y): """ x.__div__(y) <==> x/y """ pass def __eq__(self, y): """ x.__eq__(y) <==> x==y """ pass def __float__(self): """ x.__float__() <==> float(x) """ pass def __floordiv__(self, y): """ x.__floordiv__(y) <==> x//y """ pass def __format__(self, format_spec): """ float.__format__(format_spec) -> string Formats the float according to format_spec. """ return "" def __getattribute__(self, name): """ x.__getattribute__('name') <==> x.name """ pass def __getformat__(self, typestr): """ float.__getformat__(typestr) -> string You probably don't want to use this function. It exists mainly to be used in Python's test suite. typestr must be 'double' or 'float'. This function returns whichever of 'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the format of floating point numbers used by the C type named by typestr. """ return "" def __getnewargs__(self, *args, **kwargs): # real signature unknown pass def __ge__(self, y): """ x.__ge__(y) <==> x>=y """ pass def __gt__(self, y): """ x.__gt__(y) <==> x>y """ pass def __hash__(self): """ x.__hash__() <==> hash(x) """ pass def __init__(self, x): pass def __int__(self): """ x.__int__() <==> int(x) """ pass def __le__(self, y): """ x.__le__(y) <==> x<=y """ pass def __long__(self): """ x.__long__() <==> long(x) """ pass def __lt__(self, y): """ x.__lt__(y) <==> x<y """ pass def __mod__(self, y): """ x.__mod__(y) <==> x%y """ pass def __mul__(self, y): """ x.__mul__(y) <==> x*y """ pass def __neg__(self): """ x.__neg__() <==> -x """ pass @staticmethod # known case of __new__ def __new__(S, *more): """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass def __ne__(self, y): """ x.__ne__(y) <==> x!=y """ pass def __nonzero__(self): """ x.__nonzero__() <==> x != 0 """ pass def __pos__(self): """ x.__pos__() <==> +x """ pass def __pow__(self, y, z=None): """ x.__pow__(y[, z]) <==> pow(x, y[, z]) """ pass def __radd__(self, y): """ x.__radd__(y) <==> y+x """ pass def __rdivmod__(self, y): """ x.__rdivmod__(y) <==> divmod(y, x) """ pass def __rdiv__(self, y): """ x.__rdiv__(y) <==> y/x """ pass def __repr__(self): """ x.__repr__() <==> repr(x) """ pass def __rfloordiv__(self, y): """ x.__rfloordiv__(y) <==> y//x """ pass def __rmod__(self, y): """ x.__rmod__(y) <==> y%x """ pass def __rmul__(self, y): """ x.__rmul__(y) <==> y*x """ pass def __rpow__(self, x, z=None): """ y.__rpow__(x[, z]) <==> pow(x, y[, z]) """ pass def __rsub__(self, y): """ x.__rsub__(y) <==> y-x """ pass def __rtruediv__(self, y): """ x.__rtruediv__(y) <==> y/x """ pass def __setformat__(self, typestr, fmt): """ float.__setformat__(typestr, fmt) -> None You probably don't want to use this function. It exists mainly to be used in Python's test suite. typestr must be 'double' or 'float'. fmt must be one of 'unknown', 'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be one of the latter two if it appears to match the underlying C reality. Override the automatic determination of C-level floating point type. This affects how floats are converted to and from binary strings. """ pass def __str__(self): """ x.__str__() <==> str(x) """ pass def __sub__(self, y): """ x.__sub__(y) <==> x-y """ pass def __truediv__(self, y): """ x.__truediv__(y) <==> x/y """ pass def __trunc__(self, *args, **kwargs): # real signature unknown """ Return the Integral closest to x between 0 and x. """ pass imag = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """the imaginary part of a complex number""" real = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """the real part of a complex number""" float
4)复数(complex)
12.2 布尔类型
真或者假
True或者False
1或者0
12.3 字符串格式化
Python采用的格式化方式和C语言类似。%运算符就是用来格式化字符串的。在字符串内部,%s表示用字符串替换,%d表示用整数替换,有几个%?占位符,后面就跟几个变量或者值,顺序要对应好。如果只有一个%?,括号可以省略。%s永远起作用,它会把任何数据类型转换为字符串。对于Unicode字符串,用法完全一样,但最好确保替换的字符串也是Unicode字符串。有些时候,字符串里面的%是一个普通字符怎么办?这个时候就需要转义,用%%来表示一个%。
案例:
方法1: %s
name = raw_input("Please input your name:") age = int(raw_input("Please input your age:")) provice = raw_input("Please input your provice:") company = raw_input("Please input your company:") msg = ''' Infomation of user %s ------------------------- name : %s age : %2f provice : %s company : %s -----------End----------- ''' % (name,name,age,provice,company) print msg
方法2:字符拼接(n个变量拼接就要开辟n块内存空间 效率低)
name = input("Please input your name:") age = int(input("Please input your age:")) provice = input("Please input your provice:") company = input("Please input your company:") print("Infomation of:" + name + "\nname:" + name + "\nage:" + str(age) + "\npprovice:" + provice + "\ncompany:" + company)
方法3:format
>>> msg = "Hello,{name},it's been a long {age}!!! " >>> print(msg.format(name='Alex',age=34)) Hello,Alex,it's been a long 34!!! >>> >>> msg = "Hello,{0},it's been a long {1}!!!" >>> print(msg.format('Alex',34)) Hello,Alex,it's been a long 34!!!
12.2.2 字符串函数
a.capitalize( # 首字母大写 a.center( # 将字符串放到中间 a.count( # 某个字母格式统计 a.decode( # 编码转换 a.encode( # 编码转换 a.endswith( # 以xxx结尾 a.expandtabs( a.find( # 查找并返回索引值,没有返回-1 a.format( # 格式化输出 两种方法 传递变量{name} {msg} 或者 {0} {1} a.index( a.isalnum( a.isalpha( a.isdigit( # 判断是否为数字 a.islower( a.isspace( a.istitle( a.isupper( a.join( # 合并字符串 a.ljust( a.lower( # 字母全部小写 a.lstrip( a.partition( a.replace( a.rfind( a.rindex( a.rjust( a.rpartition( a.rsplit( a.rstrip( a.split( # 分割 a.splitlines( a.startswith( a.strip( # 移除空白 a.swapcase( a.title( a.translate( a.upper( # 大写 a.zfill(
class str(basestring): """ str(object='') -> string Return a nice string representation of the object. If the argument is a string, the return value is the same object. """ def capitalize(self): """ 首字母变大写 """ """ S.capitalize() -> string Return a copy of the string S with only its first character capitalized. """ return "" def center(self, width, fillchar=None): """ 内容居中,width:总长度;fillchar:空白处填充内容,默认无 """ """ S.center(width[, fillchar]) -> string Return S centered in a string of length width. Padding is done using the specified fill character (default is a space) """ return "" def count(self, sub, start=None, end=None): """ 子序列个数 """ """ S.count(sub[, start[, end]]) -> int Return the number of non-overlapping occurrences of substring sub in string S[start:end]. Optional arguments start and end are interpreted as in slice notation. """ return 0 def decode(self, encoding=None, errors=None): """ 解码 """ """ S.decode([encoding[,errors]]) -> object Decodes S using the codec registered for encoding. encoding defaults to the default encoding. errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors raise a UnicodeDecodeError. Other possible values are 'ignore' and 'replace' as well as any other name registered with codecs.register_error that is able to handle UnicodeDecodeErrors. """ return object() def encode(self, encoding=None, errors=None): """ 编码,针对unicode """ """ S.encode([encoding[,errors]]) -> object Encodes S using the codec registered for encoding. encoding defaults to the default encoding. errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors raise a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and 'xmlcharrefreplace' as well as any other name registered with codecs.register_error that is able to handle UnicodeEncodeErrors. """ return object() def endswith(self, suffix, start=None, end=None): """ 是否以 xxx 结束 """ """ S.endswith(suffix[, start[, end]]) -> bool Return True if S ends with the specified suffix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. suffix can also be a tuple of strings to try. """ return False def expandtabs(self, tabsize=None): """ 将tab转换成空格,默认一个tab转换成8个空格 """ """ S.expandtabs([tabsize]) -> string Return a copy of S where all tab characters are expanded using spaces. If tabsize is not given, a tab size of 8 characters is assumed. """ return "" def find(self, sub, start=None, end=None): """ 寻找子序列位置,如果没找到,返回 -1 """ """ S.find(sub [,start [,end]]) -> int Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure. """ return 0 def format(*args, **kwargs): # known special case of str.format """ 字符串格式化,动态参数,将函数式编程时细说 """ """ S.format(*args, **kwargs) -> string Return a formatted version of S, using substitutions from args and kwargs. The substitutions are identified by braces ('{' and '}'). """ pass def index(self, sub, start=None, end=None): """ 子序列位置,如果没找到,报错 """ S.index(sub [,start [,end]]) -> int Like S.find() but raise ValueError when the substring is not found. """ return 0 def isalnum(self): """ 是否是字母和数字 """ """ S.isalnum() -> bool Return True if all characters in S are alphanumeric and there is at least one character in S, False otherwise. """ return False def isalpha(self): """ 是否是字母 """ """ S.isalpha() -> bool Return True if all characters in S are alphabetic and there is at least one character in S, False otherwise. """ return False def isdigit(self): """ 是否是数字 """ """ S.isdigit() -> bool Return True if all characters in S are digits and there is at least one character in S, False otherwise. """ return False def islower(self): """ 是否小写 """ """ S.islower() -> bool Return True if all cased characters in S are lowercase and there is at least one cased character in S, False otherwise. """ return False def isspace(self): """ S.isspace() -> bool Return True if all characters in S are whitespace and there is at least one character in S, False otherwise. """ return False def istitle(self): """ S.istitle() -> bool Return True if S is a titlecased string and there is at least one character in S, i.e. uppercase characters may only follow uncased characters and lowercase characters only cased ones. Return False otherwise. """ return False def isupper(self): """ S.isupper() -> bool Return True if all cased characters in S are uppercase and there is at least one cased character in S, False otherwise. """ return False def join(self, iterable): """ 连接 """ """ S.join(iterable) -> string Return a string which is the concatenation of the strings in the iterable. The separator between elements is S. """ return "" def ljust(self, width, fillchar=None): """ 内容左对齐,右侧填充 """ """ S.ljust(width[, fillchar]) -> string Return S left-justified in a string of length width. Padding is done using the specified fill character (default is a space). """ return "" def lower(self): """ 变小写 """ """ S.lower() -> string Return a copy of the string S converted to lowercase. """ return "" def lstrip(self, chars=None): """ 移除左侧空白 """ """ S.lstrip([chars]) -> string or unicode Return a copy of the string S with leading whitespace removed. If chars is given and not None, remove characters in chars instead. If chars is unicode, S will be converted to unicode before stripping """ return "" def partition(self, sep): """ 分割,前,中,后三部分 """ """ S.partition(sep) -> (head, sep, tail) Search for the separator sep in S, and return the part before it, the separator itself, and the part after it. If the separator is not found, return S and two empty strings. """ pass def replace(self, old, new, count=None): """ 替换 """ """ S.replace(old, new[, count]) -> string Return a copy of string S with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced. """ return "" def rfind(self, sub, start=None, end=None): """ S.rfind(sub [,start [,end]]) -> int Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure. """ return 0 def rindex(self, sub, start=None, end=None): """ S.rindex(sub [,start [,end]]) -> int Like S.rfind() but raise ValueError when the substring is not found. """ return 0 def rjust(self, width, fillchar=None): """ S.rjust(width[, fillchar]) -> string Return S right-justified in a string of length width. Padding is done using the specified fill character (default is a space) """ return "" def rpartition(self, sep): """ S.rpartition(sep) -> (head, sep, tail) Search for the separator sep in S, starting at the end of S, and return the part before it, the separator itself, and the part after it. If the separator is not found, return two empty strings and S. """ pass def rsplit(self, sep=None, maxsplit=None): """ S.rsplit([sep [,maxsplit]]) -> list of strings Return a list of the words in the string S, using sep as the delimiter string, starting at the end of the string and working to the front. If maxsplit is given, at most maxsplit splits are done. If sep is not specified or is None, any whitespace string is a separator. """ return [] def rstrip(self, chars=None): """ S.rstrip([chars]) -> string or unicode Return a copy of the string S with trailing whitespace removed. If chars is given and not None, remove characters in chars instead. If chars is unicode, S will be converted to unicode before stripping """ return "" def split(self, sep=None, maxsplit=None): """ 分割, maxsplit最多分割几次 """ """ S.split([sep [,maxsplit]]) -> list of strings Return a list of the words in the string S, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done. If sep is not specified or is None, any whitespace string is a separator and empty strings are removed from the result. """ return [] def splitlines(self, keepends=False): """ 根据换行分割 """ """ S.splitlines(keepends=False) -> list of strings Return a list of the lines in S, breaking at line boundaries. Line breaks are not included in the resulting list unless keepends is given and true. """ return [] def startswith(self, prefix, start=None, end=None): """ 是否起始 """ """ S.startswith(prefix[, start[, end]]) -> bool Return True if S starts with the specified prefix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. prefix can also be a tuple of strings to try. """ return False def strip(self, chars=None): """ 移除两段空白 """ """ S.strip([chars]) -> string or unicode Return a copy of the string S with leading and trailing whitespace removed. If chars is given and not None, remove characters in chars instead. If chars is unicode, S will be converted to unicode before stripping """ return "" def swapcase(self): """ 大写变小写,小写变大写 """ """ S.swapcase() -> string Return a copy of the string S with uppercase characters converted to lowercase and vice versa. """ return "" def title(self): """ S.title() -> string Return a titlecased version of S, i.e. words start with uppercase characters, all remaining cased characters have lowercase. """ return "" def translate(self, table, deletechars=None): """ 转换,需要先做一个对应表,最后一个表示删除字符集合 intab = "aeiou" outtab = "12345" trantab = maketrans(intab, outtab) str = "this is string example....wow!!!" print str.translate(trantab, 'xm') """ """ S.translate(table [,deletechars]) -> string Return a copy of the string S, where all characters occurring in the optional argument deletechars are removed, and the remaining characters have been mapped through the given translation table, which must be a string of length 256 or None. If the table argument is None, no translation is applied and the operation simply removes the characters in deletechars. """ return "" def upper(self): """ S.upper() -> string Return a copy of the string S converted to uppercase. """ return "" def zfill(self, width): """方法返回指定长度的字符串,原字符串右对齐,前面填充0。""" """ S.zfill(width) -> string Pad a numeric string S with zeros on the left, to fill a field of the specified width. The string S is never truncated. """ return "" def _formatter_field_name_split(self, *args, **kwargs): # real signature unknown pass def _formatter_parser(self, *args, **kwargs): # real signature unknown pass def __add__(self, y): """ x.__add__(y) <==> x+y """ pass def __contains__(self, y): """ x.__contains__(y) <==> y in x """ pass def __eq__(self, y): """ x.__eq__(y) <==> x==y """ pass def __format__(self, format_spec): """ S.__format__(format_spec) -> string Return a formatted version of S as described by format_spec. """ return "" def __getattribute__(self, name): """ x.__getattribute__('name') <==> x.name """ pass def __getitem__(self, y): """ x.__getitem__(y) <==> x[y] """ pass def __getnewargs__(self, *args, **kwargs): # real signature unknown pass def __getslice__(self, i, j): """ x.__getslice__(i, j) <==> x[i:j] Use of negative indices is not supported. """ pass def __ge__(self, y): """ x.__ge__(y) <==> x>=y """ pass def __gt__(self, y): """ x.__gt__(y) <==> x>y """ pass def __hash__(self): """ x.__hash__() <==> hash(x) """ pass def __init__(self, string=''): # known special case of str.__init__ """ str(object='') -> string Return a nice string representation of the object. If the argument is a string, the return value is the same object. # (copied from class doc) """ pass def __len__(self): """ x.__len__() <==> len(x) """ pass def __le__(self, y): """ x.__le__(y) <==> x<=y """ pass def __lt__(self, y): """ x.__lt__(y) <==> x<y """ pass def __mod__(self, y): """ x.__mod__(y) <==> x%y """ pass def __mul__(self, n): """ x.__mul__(n) <==> x*n """ pass @staticmethod # known case of __new__ def __new__(S, *more): """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass def __ne__(self, y): """ x.__ne__(y) <==> x!=y """ pass def __repr__(self): """ x.__repr__() <==> repr(x) """ pass def __rmod__(self, y): """ x.__rmod__(y) <==> y%x """ pass def __rmul__(self, n): """ x.__rmul__(n) <==> n*x """ pass def __sizeof__(self): """ S.__sizeof__() -> size of S in memory, in bytes """ pass def __str__(self): """ x.__str__() <==> str(x) """ pass str str
13、Python相关文件格式
13.1 pyc(字节代码)
由于python程序的py文件很容易泄露源代码,所以python可以编译成保密的pyc文件。python的pyc文件是一种二进制文件,py文件变成pyc文件后,加载的速度有所提高,而且pyc是一种跨平台的字节码,是由python的虚拟机来执行的,这个是类似于JAVA或者.NET的虚拟机的概念。
编译py文件到pyc文件的方法:
在命令行输入:python -m py_compile myFile.py 就可以生成对应的pyc文件
Python 2.x 模块应用会自动产生
Python 3.x 模块应用bu会自动产生
13.2 py(源代码)
Python源代码的文件以“py”为扩展名,由python解释器解释运行。"pyw"是图形开发用户接口(GUI)文件的扩展名,作为桌面应用程序,这种文件用于开发图形界面的,由pythonw.exe解释运行。
13.3 pyo(优化代码)
优化代码:经过优化的源文件, 扩展名“pyo”
优化方法:python -o -m py_compile hello.py
-o:表示生成优化代码
-m:表示把py_compile模块作为脚本运行,编译代码需要调用 py_compile模块的complie()方法。
练习题
练习题1:用户登录
程序需求:
a、用户输入用户名和密码,验证成功打印欢迎信息
b、如果密码错误,用户登录失败,提示用户名或者密码错误
c、用户输入密码错误3次,用户锁定
d、当用户3次输入不存在的用户时,提示错误信息,并让用户等待10s再次输入
思路分析: 必须有两个文件:
1)记录用户的账号密码信息
2)记录被锁定的账号 实现顺序:
1)锁定文件扫描,存在则退出
2)记录输入次数,超过三次锁定
3)验证账号密码正确,提示信息
流程图:
代码实现:
练习题2:三级菜单 可依次选择进入各子菜单
思路分析: 如何存储省、市、县信息?
如何通过通过索引取得对应的信息?
如何保证信息的有序性? dict = { "省" : { 市:['县'] } } 即:字典加列表组合 dict.keys 省信息列表 dict['省'].keys 市信息列表 dict['省']['市'] 县信息列表
出处:http://www.cnblogs.com/madsnotes/
声明:本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。