Python的数据类型
数值类型
整数类型
In [1]: a=1
In [2]: type(a)
Out[2]: int # int表示为整型
In [18]: type(2/1)
Out[18]: int
浮点型
In [3]: a=1.23
In [4]: type(a)
Out[4]: float # float表示的是浮点数
In [19]: type(2.0/1)
Out[19]: float
长整型
In [11]: a=1299999999999999999999999999999999999999999
In [12]: type(a)
Out[12]: long #long表示长整型
In [13]: a
Out[13]: 1299999999999999999999999999999999999999999L
In [15]: a=123l
In [16]: type(a)
Out[16]: long
#只有python2.x中有长整型的概念,python3.x只有整型
复数型
In [20]: type(123j)
Out[20]: complex # 表示复数类型
字符串类型
'
或双引号
"
括起来的任意文本,比如
'abc'
,
"xyz"
等等。请注意,
''
或
""
本身只是一种表示方式,不是字符串的一部分,因此,字符串
'abc'
只有
a
,
b
,
c
这3个字符。如果
'
本身也是一个字符,那就可以用
""
括起来,比如
"I'm OK"
包含的字符是
I
,
'
,
m
,空格,
O
,
K
这6个字符。有三种方法定义字符串:单引号,双引号,三引号。
str='this is string'
str="this is string"
str='''this is string''' #也可以是三个双引号,三个引号可以多行注释但是不能单双混合
字符串的基本操作
索引
In [3]: a='1234567'
In [4]: a[0] -->#下标从0开始,0表示第一个数
Out[4]: '1'
In [5]: a[3] -->#表示第四个数
Out[5]: '4'
切片
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 In [14]: a='abcd' 2 In [15]: a[0:2] 3 Out[15]: 'ab' 4 #从第0个开始截取2个字符,其中0可以省略 5 6 7 In [14]: a='abcd' 8 In [16]: a[:-1] 9 Out[16]: 'abc' 10 #默认是从左往右(前往后),带减号,表示从右往左(后往前),-1表示最后一个字符(a='abcd',-1的值是d,也就是3,顾a[:-1],就等于a[0:3]) 11 12 13 In [14]: a='abcd' 14 In [17]: a[1:] 15 Out[17]: 'bcd' 16 #从1开始截取到最后 17 18 19 In [14]: a='abcd' 20 In [20]: a[::2] 21 Out[20]: 'aceg' 22 #步长为2,表示从0开始步长为2,(取0,2,4,6) 23 24 25 In [26]: a 26 Out[26]: 'abcdefg' 27 In [27]: a[-5:-1] 28 Out[27]: 'cdef' 29 #表示倒着取,从倒数第五个取到倒数第一个(不包含倒数第一,要想取可以使用a[-5:]) 30 31 32 In [29]: a 33 Out[29]: 'abcdefg' 34 In [30]: a[0:5:1] 35 Out[30]: 'abcde' 36 In [31]: a[0:5:2] 37 Out[31]: 'ace' 38 #从0开始取到第5个,步长为1,步长为2 39 40 41 In [32]: a 42 Out[32]: 'abcdefg' 43 In [34]: a[-1::-1] 44 Out[34]: 'gfedcba' 45 #从后往前取,步长为-1,表示每次倒着取1个,由于没有指定结尾,默认到最后,所以就把数字逆了过来。 46 47 48 In [36]: a 49 Out[36]: 'abcdefg' 50 In [38]: a[::2][:2] 51 Out[38]: 'ac' 52 #表示先每隔2个取出来,然后从头开始取2个。
字符串的内置方法
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 # 功能:首字母大写 2 # 调用方式:string.capitalize() 3 # 例: 4 name = 'hello' name.capitalize() 5 6 #结果: 7 'Hello'
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 # 3.x新增 字符串转换为小写,可以转换各种语言大小写(法语、德语...) 2 # 用法 :string.casefold() 3 4 例子: 5 name = 'HELLO' 6 name.casefold() 7 8 结果: 'hello'
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 # 功能:字符串转换为小写,只能转换英文字母 2 # 用法:string.lower() 3 4 例: 5 name = 'World' 6 name.lower() 7 8 结果: 9 'world'
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 # 功能:文本填充,width为字符串的总长度,str居中然后两端用fillcharacter填充,fillchar默认为空格 2 # 用法:str.center(width,filechar=None) 3 4 例: 5 name = 'hello' 6 name.center(7,'*') 7 8 结果: 9 *hello*
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 # 功能:sub为统计的字符串(子序列),统计sub出现的次数,start为起始位置,end为结尾位置 2 # 用法:str.counter(sub,start=None,end=None) 3 4 例: 5 name = 'hello' 6 name.counter('l') 7 8 结果: 9 2
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 # 功能:以suffix为开头,返回bool值,start起始位置,end结束位置 2 # 用法:str.startswith(suffix,start=None,end=None) 3 4 例: 5 name = 'Hello' 6 name.startswith('H') 7 8 结果: 9 True
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 # 功能:以suffix为结尾,返回bool值,start起始位置,end结束位置 2 # 用法:str.endswith(suffix,start=None,end=None) 3 4 例: 5 name = 'world' 6 name.endswith('d') 7 8 结果: 9 True
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 # 功能:找到tab键,然后对它做一个特殊的替换,20表示,两个\t之前的总和(开头没有的话,默认从开头开始) 2 # 用法:str.expendtabs(20) 3 4 例: 5 name = 'a\tb\tc\t' 6 name.expendtabs(3) 7 8 结果: 9 'a b c' 10 11 解读:中间两个空格,算上单字符串和空格,总长度为3。
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 # 功能:找到sub在str中的位置,如果找到返回index(匹配到第一个),找不到返回-1 2 # 用法:str. find(sub,start=None,end=None) 3 4 例: 5 name = 'hello' 6 name.find('l') 7 8 结果: 9 2
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 # 功能:格式化字符串,位置占位符为{0},{1} 2 # 用法:str.format() 3 4 例: 5 print("Hello {0},I'am {1}".format('daxin','20')) 6 7 结果: 8 Hello daxin,I'am 20 9 10 扩展: 11 可以命名占位符{name},{age},那么赋值的时候就需要 name=daxin,age=2
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 # 功能:格式化字符串,只不过传递的值是一个字典 2 # 用法:str.format_map() 3 4 例:接上个例子 5 print("hello {name},I am {age}".formar({'name':"daxin",'age'=20}))
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 # 功能:查询sub在str中的index,如果不存在,会报错 2 # 用法:str.index(sub) 3 4 例: 5 name = 'hello world' 6 name.index('w') 7 8 结果: 9 6
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 # 功能:判断str中是否包含数字,字母,汉字等等,然后bool 2 # 用法:str.isalnum() 3 4 例: 5 name = 'abc123你好' 6 name.isalnum() 7 8 结果: 9 True
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 # 功能:判断字符串是否都为字母,返回bool类型 2 # 用法:str.isalpha() 3 4 例: 5 name = 'abc123' 6 name.isalpha() 7 8 结果: 9 False
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 # 功能:判断是否只包含阿拉伯数字,'123' 2 # 用法:str. isdecimal() 3 4 例: 5 name = '123' 6 name.isdecimal() 7 8 结果: 9 True
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 # 功能:只能认识阿拉伯数字、以及特殊符号的数字,'123','②' 2 # 用法:str. isdigit() 3 4 例: 5 name = '123②二' 6 name.digit() 7 8 结果: 9 False
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 # 功能:只能认识阿拉伯数字、以及特殊符号的数字,以及中文数字'123','②','二' 2 # 用法:str. isnumerice() 3 4 例: 5 name = '123②二' 6 name.isnumerice() 7 8 结果: 9 True
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 # 功能:判断对象是否可以成为标识符(变量名)来用,不会判断关键字 2 # 用法:str.isidentifier() 3 4 例: 5 name = '9hello' 6 name.isidentifier() 7 8 结果: 9 False
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 # 功能:str是否都是小写,返回bool 2 # 用法:str. islower() 3 4 例: 5 name = 'hello' 6 name.islower() 7 8 结果: 9 True
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 # 功能:str是否是大写,返回bool类型 2 # 用法:str. isupper() 3 4 例: 5 name = 'HELLO' 6 name.isuper() 7 8 结果: 9 True
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 # 功能:把str转换为大写 2 # 用法:str.upper() 3 4 例: 5 name = 'hello' 6 name.upper() 7 8 结果: 9 'HELLO'
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 # 功能:判断对象是否可以被打印(不包含隐藏字符,例如\n,这种打印不出来的,就会返回False) 2 # 用法:str.isprintable() 3 4 例: 5 name = 'hello\n' 6 name.isprintable() 7 8 结果: 9 False
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 # 功能:判断对象是否是空格 2 # 用法:str.isspace() 3 4 例: 5 name = ' ' 6 name.isspace() 7 8 结果: 9 True
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 # 功能:判断对象是否是标题,既首字母大写(既每个单词的首字母大写) 2 # 用法:str.stitle() 3 4 例: 5 name = 'Hello World' 6 name.istitle() 7 8 结果: 9 True
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 # 功能:连接,用于把可迭代对象的每个元素用 什么 连接起来,可迭代对象的元素必须是str 2 # 用法:'分隔符'.join(iterable) 3 4 例1: 5 a = 'hello' 6 '*'.join(a) 7 结果: 8 h*e*l*l*o 9 10 例2: 11 '*'.join([ str(i) for i in range(10)])
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 # 功能:左填充,fillchar为填充的字符 2 # 用法:str.ljust(width,fillchar=None) 3 4 例: 5 name = 'hello' 6 name.ljust(10,'*') 7 8 结果: 9 *****hello
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 # 功能:右填充,fillchar为填充的字符 2 # 用法:str.rjust(width,fillchar=None) 3 4 例: 5 name = 'hello' 6 name.rjust(10,'*') 7 8 结果: 9 hello*****
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 # 功能:左去除,既删除左边的空格换行符和制表符 2 # 用法:str.lstrip() 3 4 例: 5 name = '*hello*' 6 name.lstrip('*') 7 8 结果: 9 'hello*'
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 # 功能:右去除,既删除右边的空格换行符和制表符 2 # 用法:ste.rstrip() 3 4 例: 5 name = '*hello*' 6 name.rstrip('*') 7 8 结果: 9 '*hello'
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 # 功能:创建对应关系,既a对应1,b对应2,c对应3 2 # 用法:str.maketrans('abc','123') 3 4 例: 5 m = str.maketrans('abc','123') 6 name = 'abc123' 7 v = name.translate(m) 8 print(v) 9 10 结果: 11 '123123'
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 # 功能:和maketrans连用,用来表示按照什么规则进行翻译解释,例子如上 2 # 用法:str.translate()
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 # 功能:根据split进行分割,从左开始,只分割遇到的一个split,并且保存分隔符,返回的对象为元祖 2 # 用法:str.partition('split') 3 4 例: 5 name = 'Hello|World' 6 name.partition('|') 7 8 结果: 9 ('hello','|','World')
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 # 功能:字符串的替换,把src替换为dst,counter为替换几次 2 # 用法:str.replice('src','dst',counter=None) 3 4 例: 5 name = 'Hello World' 6 name.replice('H','h') 7 8 结果: 9 'hello World'
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 # 功能:右查找,既丛字符串的右边开始查找sub,并返回它对应的index 2 # 用法:str.rfind('sub') 3 4 例: 5 name = 'hello' 6 name.rfind('l') 7 8 结果: 9 3
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 # 功能:从右边查找sub的index,如果sub在str对象中不存在,那么会报valueError异常 2 # 用法:str.rindex('sub') 3 4 例: 5 name = 'hello' 6 name.rindex('l') 7 8 结果: 9 3
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 # 功能:既从右边开始,对找到的第一个split进行分割,返回值为元祖(包含分隔符) 2 # 用法:str.rpatition('split') 3 4 例: 5 name = 'hello' 6 name.rpatition('l') 7 8 结果: 9 ('hel','l','o')
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 # 功能:把字符串默认从左开始对象使用split进行分割,默认会对所有分割符进行分割,num可以指定分隔符的个数 2 # 用法:str.split('split',num=None) 3 4 例1: 5 name = 'hello world' 6 name.split('l') 7 结果: 8 ['he','','o wor','d'] 9 10 例2: 11 name = 'hello world' 12 name.split('l',1) 13 结果: 14 ['he','lo world']
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 # 功能:把字符串从右开始使用split进行分割,在不指定num的情况下和split相同 2 # 用法:str.rsplit('split',num=None) 3 4 例: 5 name = 'hello world' 6 name.rsplit('l',1) 7 8 结果: 9 ['hello wor','d']
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 # 功能:以什么为分行符,功能等同于split('\n') 2 # 用法:str.splitlines(keepends=None) 3 4 例: 5 name = 'hello\nworld' 6 name.splitlines('\n')
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 # 功能:去除两边的string,默认是移除空格换行及制表符。 2 # 用法:str.strip('string') 3 4 例: 5 name = ' hello ' 6 name.strip() 7 8 结果: 9 'hello'
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 # 功能:大小写转换,既把对象的大写转换为小写,小写转换为大写 2 # 用法:str. swapcase() 3 4 例: 5 name = 'Hello' 6 name.swapcase() 7 8 结果: 9 'hELLO'
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 # 功能:把单词的首字母换成大写 2 # 用法:str.title() 3 4 例: 5 name = 'hello' 6 name.title() 7 8 结果: 9 'Hello'
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 # 功能:在字符串的左边填充0,width为总长度 2 # 用法:str.zfill(width) 3 4 例: 5 name ='hello' 6 name.zfill(10) 7 8 结果: 9 '00000hello'
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 # 功能:把字符串转换为二进制(字节类型),encodinf=UTF-8,表示转换的时候按照UTF-8进行编码 2 # 用法:str.encode(encoding = 'UTF-8') 3 4 例: 5 name = '你好' 6 name.encode(encoding='UTF-8') 7 8 结果: 9 b'\xe4\xbd\xa0\xe5\xa5\xbd' 10 11 扩展: 12 也可以用其他的编码类型如:gbk
# format补充
print('{} * {} = {:5}'.format(1,2,3) # 这里说的括号中的:5表示当前元素替换占用5个位置
print('{} * {} = {:<5}'.format(1,2,3) # 这里的<表示左对齐,默认情况下是右对齐,当前这里也可以用>表示右多对齐
# 对齐符下的括号嵌套
print('{} * {} = {:>{}}'.format(1,2,3, 2 if True else 3) # 这里按照括号边界来区分,很明显嵌套在括号里面的的占位符是4。
# 如果不是用在对齐符中,那么就无法进行嵌套
序列类型
序列类型的基本操作方法
序列同样支持索引和切片操作,但是字符串、列表、元组的索引和切片又有些许不通
len()
In [7]: a='123'
In [8]: len(a)
Out[8]: 3
In [9]: len('123')
Out[9]: 3
+
In [10]: a
Out[10]: '123'
In [11]: a + '4'
Out[11]: '1234'
#字符串和数字不能连接到一起
*
In [18]: '#' * 10
Out[18]: '##########'
#当变量为数字的时候就为乘了。
in
In [23]: a = 'abcd'
In [24]: 'a' in a
Out[24]: True
#当字符串在某个序列中的时候返回真,否则返回假(not in表示不在)
max(),min()
In [25]: max(a)
Out[25]: 'd'
In [26]: min(a)
Out[26]: 'a'
In [27]: a
Out[27]: 'abcd'
注意:如果对字符进行对比,程序内部会把字符转换成ascii码对应的数字进行比较。
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 >>> ord('a') 2 97 3 >>> ord('b') 4 98 5 >>> ord('c') 6 99 7 >>>
cmp()
比较两个序列是否相等
#若相等则返回0,若前大于后则返回正数,若后大于前则返回负数
In [30]: cmp("123","456")
Out[30]: -1
In [33]: cmp("789","456")
Out[33]: 1
In [34]: cmp("456","456")
Out[34]: 0
#注意cmp的比较是从左向右开始比对的,大于就返回1,小于就返回-1,等于就继续向后比对
In [43]: cmp('5','456')
Out[43]: 1
In [44]: cmp('45','456')
Out[44]: -1
In [45]: cmp('455','456')
Out[45]: -1
In [46]: cmp('457','456')
Out[46]: 1
元组概念
元祖的特点
In [8]: a='123456'
In [9]: a[-1]
Out[9]: '6'
In [10]: a[-1]=1
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-10-1ad23d7f375d> in <module>()
----> 1 a[-1]=1
TypeError: 'str' object does not support item assignment
In [11]:
#变量a是可以被定义成任何值的,但是不能在定义之后,修改里面的值,如果想要修改就需要重新定义这个变量
In [11]: a='123451'
In [13]: a[-1]
Out[13]: '1'
定义一个元组
In [18]: t=(1)
In [19]: type(t)
Out[19]: int
In [20]: t=(1,)
In [21]: type(t)
Out[21]: tuple # tuple表示元组类型
#引用其他元组
In [22]: a=(1,2,3)
In [23]: t=('123',a)
In [24]: t
Out[24]: ('123', (1, 2, 3))
#通过索引只引用某一个值
In [27]: t=('123',a[1])
In [28]: t
Out[28]: ('123', 2)
元祖的基本操作方法
元组和其他数据类型相同,它支持的操作如下。
元祖的拆分
In [34]: a=('123','456')
In [35]: first,second=a --> # 定义first接收元组的第一个值,second接收元组的第二个值
In [36]: first
Out[36]: '123'
In [37]: second
Out[37]: '456'
#注意接收值的变量要与元组中的值的个数保持一致,若元组中有3个值,必须定义三个变量去接收,否则无法接收(当元组中有两个值的时候,用一个变量去接不会报错,但是也还是用元组的形式表达)
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 >>> a = ('a','b','c','d') 2 >>> a,b,_,d = a 3 >>> a 4 'a' 5 >>> b 6 'b' 7 >>> d 8 'd' 9 >>>
元组的方法
# 会列出一些内饰的属性,和方法
>>> dir(a)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']
>>>
# 已__开头的先忽略,后面会讲,所以可以看到有两个方法。
# 使用help查看使用方法
In [3]: help(a.count)
count(...)
T.count(value) -> integer -- return number of occurrences of value
# a.count(value) 用来统计value在元组中出现的次数,不存在返回0。
In [4]: a=('1','2','3')
In [7]: a.count("4")
Out[7]: 0
In [8]: a.count("1")
Out[8]: 1
# a.index(value) 用来返回value在元组中的索引,如果value不在元组中,则会报错。如果有多个,默认返回第一个(可以指定从哪个索引开始查找到某个索引结束,指定范围区间)
In [4]: a=('1','2','3')
In [9]: a.index('1')
Out[9]: 0
In [10]: a.index('3')
Out[10]: 2
>>> t1
('a', 'b', 'a', 'b', 'a', 'b', 'a', 'b')
>>> t1.index('a',5,7)
6
列表类型
列表的基本操作
list是一种有序的集合,可以随时添加和删除其中的元素。它的方法有很多,这里列举主要的方法。
创建一个空的列表
# 1、创建一个空列表
list1 = []
list2 = list() # 工厂函数
# 2、创建列表并赋值
list3 = ['a',1,2]
# 3、列表可以包含变量,元组,列表等
In [15]: a=123
In [16]: b=['123',a,(1,),["hello","python"]]
In [17]: b
Out[17]: ['123', 123, (1,), ['hello', 'python']]
In [24]: len(b)
Out[24]: 4
#一共有4个变量
# 4、列表的值是可以改变的
In [25]: b
Out[25]: ['123', 123, (1,), ['hello', 'python']]
In [26]: b[0]
Out[26]: '123'
In [27]: b[0]=456
In [29]: b
Out[29]: [456, 123, (1,), ['hello', 'python']]
列表的追加
使用append在list的后面(右边)
In [30]: a=[]
In [31]: type(a)
Out[31]: list
In [32]: a.append("linux")
In [33]: a
Out[33]: ['linux']
列表的组合
使用+,对多个列表进行拼接
In [32]: a = [456, 123, (1,)]
In [33]: b = [['hello', 'python'], 'linux']
In [34]: b + a
Out[34]: [456, 123, (1,), ['hello', 'python'], 'linux']
In [35]: (b + a) * 2 # 重复2次
Out[35]:[456, 123, (1,), ['hello', 'python'], 'linux', 456, 123, (1,), ['hello', 'python'], 'linux']
>>>
列表的删除
使用list的remove方法删除一个元素
In [38]: b = [456, 123, (1,), ['hello', 'python'],'love']
In [39]: b.remove('love')
In [40]: b
Out[40]: [456, 123, (1,), ['hello', 'python']]
#直接移出元素名,如果有两个,则默认删除匹配的第一个。
In [55]: b
Out[55]: [123, 456, ['hello', 'python'], '123', (1,)]
In [56]: del b[0]
In [57]: b
Out[57]: [456, ['hello', 'python'], '123', (1,)]
#如果知道变量的索引可以直接通过del来进行删除,del还可以直接删除变量
列表的反转
使用list的reverse方法进行原地倒序。
In [41]: b = [456,123, (1,),['hello', 'python']]
In [42]: b.reverse()
In [43]: b
Out[43]: [['hello', 'python'], (1,), 123, 456]
列表的插入
使用list的insert进行数据的插入
In [47]: b
Out[47]: [456, 123, (1,), ['hello', 'python']]
In [48]: b.insert(0,'123')
In [49]: b
Out[49]: ['123', 456, 123, (1,), ['hello', 'python']]
# 在索引0的位置插入一个元素‘123’
查找列表中变量
In [62]: b
Out[62]: [456, ['hello', 'python'], '123', (1,)]
In [63]: '123' in b
Out[63]: True
In [65]: "a" in b
Out[65]: False
# 存在返回True,否则返回False
变量的修改
In [68]: b
Out[68]: [456, ['hello', 'python'], '123', (1,)]
In [69]: b[0]='123'
In [70]: b
Out[70]: ['123', ['hello', 'python'], '123', (1,)]
# 修改b的索引0的元素值为‘123’
列表里面嵌入列表,并插入数据
In [71]: b=[] # 定义一个空列表
In [72]: a=[b,'123','456']
In [73]: a
Out[73]: [[], '123', '456']
In [74]: a[0].append("linux") # 向签到的b(空列表)中插入数据
In [75]: a
Out[75]: [['linux'], '123', '456']
删除并列出列表中的某个值
不加下标,表示删除并打印最后一个值,使用list的pop方法,弹出并打印指定的索引元素,如果不指定元素,则从右开始依次弹出一个
In [75]: a
Out[75]: [['linux'], '123', '456']
In [76]: a.pop(1)
Out[76]: '123'
In [77]: a
Out[77]: [['linux'], '456']
添加可迭代的值
可迭代:可以理解为可以使用for循环等,挨个取出的值的列表
列表,字符串,序列,元组 都属于可迭代的对象
In [125]: a
Out[125]: [1, 3, 5, 7, 9]
In [126]: a.extend('2468')
In [127]: a
Out[127]: [1, 3, 5, 7, 9, '2', '4', '6', '8']
In [128]: b=(1,2,3,4)
In [129]: a.extend(b)
In [130]: a
Out[130]: [1, 3, 5, 7, 9, '2', '4', '6', '8', 1, 2, 3, 4]
In [131]:
In [131]: c=123
In [132]: a.extend(c)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-132-49130b702eb2> in <module>()
----> 1 a.extend(c)
TypeError: 'int' object is not iterable
In [133]: # c是int型,不是可迭代,所以会报类型错误。
列表的组合
zip(),可以把两个列表组合成一个,前一个列表去一个,后列表取一个
In [5]: list1=['Name','age']
In [6]: list2=['Tom',20]
In [7]: zip(list1,list2)
Out[7]: [('Name', 'Tom'), ('age', 20)]
字典类型
字典的方法
字典有很多的方法,这里仅列举常用的方法,其他方法可以使用dir(dict)查看
-
- keys() 获取字典的key
- values() 获取字典中所有的values
- items() 把字典转换成列表
- get() 如果字典中有该key,则返回key值,如果没有,则返回空,也可以自己定义返回值
- dic.get('Name','python'),如果存在name,则返回values,否则返回Python
- has_key('key') 判断key的是否存在,存在返回True,否则返回False
- dic1 = dic.copy() 拷贝字典到一个新的字典中去
- clear() 清除字典中的元素
- pop() 删除一个key,同时打印该key的value,如果key不存在,则返回keyerror,或者指定返回值 dic.pop('name',True)
- update() 把一个字典更新(添加)到另一个字典中
- fromkeys(s,value) 把序列s,作为字典的key,如果不给value,则默认是none,如果指定value,那么所有key对应的值都为value
字典的操作示例
创建字典
dic={}
a=dict()
dict(x=10,y=20)
dict([('a',10),('b',20)])
# 使用dict函数时,必须是以元组的形式创建。
把数据存入字典
dic = {}
dic['name'] = 'daxin'
dic['age'] = 18
for 循环打印字典
for i in d1:print i,d1[i]
# 取出字典中的key,同时可以根据key来取出value
for k,v in d1.items():print k,v
# 把字典的值转换为列表,然后利用k和v来接受列表中元组的key和value
# for 循环的知识将在下一章进行讲解
字典练习
#!/usr/bin/env python
# _*_coding:utf-8_*_
# __time__: 2017/10/17 22:54
# __author__: daxin
# __file__: text.py∂
info = dict()
name = raw_input('Please input name: ')
age = raw_input('Please input age: ')
sex = raw_input('Please input sex: ')
info['name'] = name
info['age'] = age
info['sex'] = sex
print info.items()
for k, v in info.items():
print "%s:%s " % (k, v)
PS:以上代码示例均在Python 2.7上进行测试! Python 3.x 会有区别!
类型转换
注意虽然在Python中有很多的数据类型,但是这些类型是可以相互转换的,那么就要用到了俗称工厂函数的东西:str、list、dict、tuple等等。
- str():用于把整型、浮点型等转换为字符串
- list():用于把一个可迭代对象转换为列表
- dict():把一个可迭代对象(每次迭代返回两个数据),转换为字典
- tuple():把一个可迭代对象转换为元组
# 1、 把数字转换成字符串
>>> a = 10
>>> type(a)
<class 'int'>
>>> b = str(a)
>>> type(b)
<class 'str'>
>>> print(b)
10
# 2、把list转换成字符串
>>> a = ['h','e','l','l','o']
>>> ''.join(a)
'hello'
>>>
# 注意list转换为字符串要使用join,不能用str
# 3、使用dict转换字典
>>> c = [(1,2),(3,4)]
>>> dict(c)
{1: 2, 3: 4}
>>>
注意:
工厂函数,还可以直接用来创建一个空对象。
>>> d = dict()
>>> d
{}
>>> e = str()
>>> e
''
>>> f = list()
>>> f
[]
>>>
运算符表达式
赋值运算符
算数运算符
关系运算符
逻辑运算符
其他特殊符号
练习
input方式
#!/usr/bin/env python
# _*_coding:utf-8_*_
# __time__: 2017/10/17 22:54
# __author__: daxin
# __file__: text.py∂
num1 = input("Please input a number:")
num2 = input("Please input a number:")
print " %s + %s = %s " % (num1,num2,num1+num2)
print " %s - %s = %s " % (num1,num2,num1-num2)
print " %s * %s = %s " % (num1,num2,num1*num2)
print " %s / %s = %s " % (num1,num2,num1/num2)
raw_input
#!/usr/bin/env python
# _*_coding:utf-8_*_
# __time__: 2017/10/17 22:54
# __author__: daxin
# __file__: text.py∂
num1 = int(raw_input("Please input a number:"))
num2 = int(raw_input("Please input a number:"))
print " %s + %s = %s " % (num1,num2,num1+num2)
print " %s - %s = %s " % (num1,num2,num1-num2)
print " %s * %s = %s " % (num1,num2,num1*num2)
print " %s / %s = %s " % (num1,num2,num1/num2)
小结
#把input输入的数字保存到变量num1中
#把input输入的数字保存到变量num2中
#print打印,%s表示字符串型占位符,占位符需要用“”引起来,前面几个占位符,就需要用传递几个值。外面的% 表示后面是传递的值,多个值用括号括起来
#由于raw_input是以字符串格式存储的,所以如果输入的数字并且需要计算,那么就需要强制转换为整型(int)
#这里如果求余,需要使用%,但是%和占位符的%会产生冲突,为了格式化这个符号,可以使用%%来表示
关于Print的小技巧
print(r'hello \nworld')
# 打印时,并不会去解释\n,而是直接会输出\n
str = r'hello \nworld'
# 存入的变量字符串,也不会去解释\n。
由于数据类型比较多,每个类型的方法也比较多,很多我们都记不过来,所以这里我们只需要记住常用的方法,其他的方法可以使用帮助来查询。
这里主要使用三种方式进行查询:
- dir():获取对象的方法
- help():获取对象的方法以及用法说明
- PyCharm:按住command点击类型,即可查看源码。从源码中查看对象类型的方法。
>>> help(dict)
Help on class dict in module builtins:
class dict(object)
| dict() -> new empty dictionary
| dict(mapping) -> new dictionary initialized from a mapping object's
| (key, value) pairs
| dict(iterable) -> new dictionary initialized as if via:
| d = {}
| for k, v in iterable:
| d[k] = v
| dict(**kwargs) -> new dictionary initialized with the name=value pairs
| in the keyword argument list. For example: dict(one=1, two=2)
|
| Methods defined here:
|
| __contains__(self, key, /)
| True if D has a key k, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(...)
| x.__getitem__(y) <==> x[y]
|
| __gt__(self, value, /)
| Return self>value.
|
| __init__(self, /, *args, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
|
| __repr__(self, /)
| Return repr(self).
|
| __setitem__(self, key, value, /)
| Set self[key] to value.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| fromkeys(iterable, value=None, /) from builtins.type
| Returns a new dict with keys from iterable and values equal to value.
|
| get(...)
| D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
| If key is not found, d is returned if given, otherwise KeyError is raised
|
| popitem(...)
| D.popitem() -> (k, v), remove and return some (key, value) pair as a
| 2-tuple; but raise KeyError if D is empty.
|
| setdefault(...)
| D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __hash__ = None
>>> dir(dict)
['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
>>>
注意:
__开头的是Python的内置方法,这个在类的时候,大部分会讲到。