python数据类型(string/list/tuple/dict)内置方法

Python 字符串常用方法总结

明确:对字符串的操作方法都不会改变原来字符串的值

1,去掉空格和特殊符号

name.strip()  去掉空格和换行符

name.strip('xx')  去掉某个字符串

name.lstrip()  去掉左边的空格和换行符

name.rstrip()  去掉右边的空格和换行符

2,字符串的搜索和替换

name.count('x')  查找某个字符在字符串里面出现的次数

name.capitalize()  首字母大写

name.center(n,'-')   把字符串放中间,两边用- 补齐

name.find('x')   找到这个字符返回下标,多个时返回第一个;不存在的字符返回-1

name.index('x') 找到这个字符返回下标,多个时返回第一个;不存在的字符报错

name.replace(oldstr, newstr)  字符串替换

name.format() 字符串格式化

name.format_map(d)  字符串格式化,传进去的是一个字典

Year {} Rs. {:.2f}".format(year, value) 称为字符串格式化,大括号和其中的字符会被替换成传入 str.format() 的参数,也即 year 和 value。其中 {:.2f} 的意思是替换为 2 位精度的浮点数。

{:5d} 的意思是替换为 5 个字符宽度的整数,宽度不足则使用空格填充。

 

 divmod(num1,num2)返回一个元组,这个元组包含两个值,第一个是num1 与 num2 相整除得到的值,第二个是num1 与 num2 求余得到的值

用 * 运算符查封这两个元组,得到这两个值。

等价于

3,字符串的测试和替换函数

S.startswith(prefix[,start[,end]]) 
#是否以prefix开头 
S.endswith(suffix[,start[,end]]) 
#以suffix结尾 
S.isalnum() 
#是否全是字母和数字,并至少有一个字符 
S.isalpha() #是否全是字母,并至少有一个字符 
S.isdigit() #是否全是数字,并至少有一个字符 
S.isspace() #是否全是空白字符,并至少有一个字符 
S.islower() #S中的字母是否全是小写 
S.isupper() #S中的字母是否便是大写 
S.istitle() #S是否是首字母大写的

4,字符串的分割

name.split()  默认是按照空格分割

name.split(',')   按照逗号分割

5,连接字符串

‘,’.join(slit)      用逗号连接slit 变成一个字符串,slit 可以是字符,列表,字典(可迭代的对象)

                        int 类型不能被连接

 6,截取字符串(切片)

str = '0123456789′
print str[0:3] #截取第一位到第三位的字符
print str[:] #截取字符串的全部字符
print str[6:] #截取第七个字符到结尾
print str[:-3] #截取从头开始到倒数第三个字符之前
print str[2] #截取第三个字符
print str[-1] #截取倒数第一个字符
print str[::-1] #创造一个与原字符串顺序相反的字符串
print str[-3:-1] #截取倒数第三位与倒数第一位之前的字符
print str[-3:] #截取倒数第三位到结尾
print str[:-5:-3] #逆序截取

7.string 模块

import string 

string.ascii_uppercase  所有大写字母
string.ascii_lowercase 所有小写字母
string.ascii_letters  所有字母
string.digits  所有数字

python列表的常用操作方法小结

1.创建列表。只要把逗号分隔的不同的数据项使用方括号括起来即可
List = ['wade','james','bosh','haslem']
与字符串的索引一样,列表索引从0开始。列表可以进行截取、组合等

2.添加新的元素

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

List.append('allen') #方式一:向list结尾添加 参数object

>>> a=[1,2,3,4]

>>> a.append(5)

>>> print(a)

[1, 2, 3, 4, 5]

List.insert(4,'lewis') #方式二:插入一个元素 参数一:index位置 参数二:object

>>> a=[1,2,4]

>>> a.insert(2,3)

>>> print(a)

[1, 2, 3, 4]

List.extend(tableList) #方式三:扩展列表,参数:iterable参数

>>> a=[1,2,3]

>>> b=[4,5,6]

>>> a.extend(b)

>>> print(a)

[1, 2, 3, 4, 5, 6]

3.遍历列表

?

1

2

for i in List:

   print i,

4.访问列表中的值
使用下标索引来访问列表中的值,同样你也可以使用方括号的形式截取字符,如下所示:

?

1

2

3

>>> List = [1, 2, 3, 4, 5, 6, 7 ]

>>> print(List[3])

4

5.从list删除元素

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

List.remove()  #删除方式一:参数object 如有重复元素,只会删除最靠前的

>>> a=[1,2,3]

>>> a.remove(2)

>>> print(a)

[1, 3]

List.pop()  #删除方式二:pop 可选参数index删除指定位置的元素 默认为最后一个元素

>>> a=[1, 2, 3, 4, 5, 6]

>>> a.pop()

6

>>> print(a)

[1, 2, 3, 4, 5]

del List #删除方式三:可以删除整个列表或指定元素或者列表切片,list删除后无法访问。

>>> a=[1, 2, 3, 4, 5, 6]

>>> del a[5]

>>> print(a)

[1, 2, 3, 4, 5]

>>> del a

>>> print(a)

Traceback (most recent call last):

 File "<pyshell#93>", line 1, in <module>

  print(a)

6.排序和反转代码

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

List.reverse()

>>> a=[1, 2, 3, 4, 5, 6]

>>> a.reverse()

>>> print(a)

[6, 5, 4, 3, 2, 1]

List.sort() #sort有三个默认参数 cmp=None,key=None,reverse=False 因此可以制定排序参数

>>> a=[2,4,6,7,3,1,5]

>>> a.sort()

>>> print(a)

[1, 2, 3, 4, 5, 6, 7]

#python3X中,不能将数字和字符一起排序,会出现此报错

>>> a=[2,4,6,7,3,1,5,'a']

>>> a.sort()

Traceback (most recent call last):

 File "<pyshell#104>", line 1, in <module>

  a.sort()

TypeError: unorderable types: str() < int()

7.Python列表截取
Python的列表截取与字符串操作类型相同,如下所示:
L = ['spam', 'Spam', 'SPAM!']
操作:

?

1

2

3

4

Python 表达式 结果 描述

L[2] 'SPAM!' 读取列表中第三个元素

L[-2] 'Spam' 读取列表中倒数第二个元素

L[1:] ['Spam', 'SPAM!'] 从第二个元素开始截取列表

8.Python列表操作的函数和方法
列表操作包含以下函数:
1、cmp(list1, list2):比较两个列表的元素 (python3已丢弃)
2、len(list):列表元素个数 
3、max(list):返回列表元素最大值 
4、min(list):返回列表元素最小值 
5、list(seq):将元组转换为列表 
列表操作常用操作包含以下方法:
1、list.append(obj):在列表末尾添加新的对象
2、list.count(obj):统计某个元素在列表中出现的次数
3、list.extend(seq):在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)
4、list.index(obj):从列表中找出某个值第一个匹配项的索引位置
5、list.insert(index, obj):将对象插入列表
6、list.pop(obj=list[-1]):移除列表中的一个元素(默认最后一个元素),并且返回该元素的值
7、list.remove(obj):移除列表中某个值的第一个匹配项
8、list.reverse():反向列表中元素
9、list.sort([func]):对原列表进行排序

Python 元组(Tuple)操作详解

一、tuple也是一个class,是不可变的list类型,不可以增删改。

创建:

tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5 );
tup3 = "a", "b", "c", "d";

访问:(与list一样)tup1[1:5];

修改:不可以修改,只能增加新的部分;

tup3 = tup1 + tup2;
print tup3;

 

二、任意无符号的对象,以逗号隔开,默认为元组,如下实例:

a=1,2,3,'e'

a=(1,2,3,'e').

三、Python元组包含了以下内置函数(与list差不多的函数)
1、cmp(tuple1, tuple2):比较两个元组元素。
2、len(tuple):计算元组元素个数。
3、max(tuple):返回元组中元素最大值。
4、min(tuple):返回元组中元素最小值。
5、tuple(seq):将列表转换为元组。

四、tuple的方法:

1、count():查找元素在tuple中出现的次数。

2.index():查找元素的第一个索引值。

五、Tuple 是不可变 list。 一旦创建了一个 tuple 就不能以任何方式改变它。

①、Tuple 与 list 的相同之处

定义 tuple 与定义 list 的方式相同, 除了整个元素集是用小括号包围的而不是方括号。
Tuple 的元素与 list 一样按定义的次序进行排序。 Tuples 的索引与 list 一样从 0 开始, 所以一个非空 tuple 的第一个元素总是 t[0]。
负数索引与 list 一样从 tuple 的尾部开始计数。
与 list 一样分片 (slice) 也可以使用。注意当分割一个 list 时, 会得到一个新的 list ;当分割一个 tuple 时, 会得到一个新的 tuple。

②、Tuple 不存在的方法

您不能向 tuple 增加元素。Tuple 没有 append 或 extend 方法。
您不能从 tuple 删除元素。Tuple 没有 remove 或 pop 方法。
然而, 您可以使用 in 来查看一个元素是否存在于 tuple 中。

③、用 Tuple 的好处

Tuple 比 list 操作速度快。如果您定义了一个值的常量集,并且唯一要用它做的是不断地遍历它,请使用 tuple 代替 list。
如果对不需要修改的数据进行 “写保护”,可以使代码更安全。使用 tuple 而不是 list 如同拥有一个隐含的 assert 语句,说明这一数据是常量。如果必须要改变这些值,则需要执行 tuple 到 list 的转换。

④、Tuple 与 list 的转换

Tuple 可以转换成 list,反之亦然。内置的 tuple 函数接收一个 list,并返回一个有着相同元素的 tuple。而 list 函数接收一个 tuple 返回一个 list。从效果上看,tuple 冻结一个 list,而 list 解冻一个 tuple。

python的字典常用方法

字典是一种通过名字或者关键字引用的得数据结构,其键可以是数字、字符串、元组,这种结构类型也称之为映射。字典类型是Python中唯一內建的映射类型,基本的操作包括如下: 
(1)len():返回字典中键—值对的数量; 
(2)d[k]:返回关键字对于的值; 
(3)d[k]=v:将值关联到键值k上; 
(4)del d[k]:删除键值为k的项; 
(5)key in d:键值key是否在d中,是返回True,否则返回False。

一、字典的创建 
1.1 直接创建字典

d={'one':1,'two':2,'three':3}
print d
print d['two']
print d['three']
运算结果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three': 3, 'two': 2, 'one': 1}
2
3
>>> 

1.2 通过dict创建字典

# _*_ coding:utf-8 _*_
items=[('one',1),('two',2),('three',3),('four',4)]
print u'items中的内容:'
print items
print u'利用dict创建字典,输出字典内容:'
d=dict(items)
print d
print u'查询字典中的内容:'
print d['one']
print d['three']
运算结果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
items中的内容:
[('one', 1), ('two', 2), ('three', 3), ('four', 4)]
利用dict创建字典,输出字典内容:
{'four': 4, 'three': 3, 'two': 2, 'one': 1}
查询字典中的内容:
1
3
>>> 

或者通过关键字创建字典

# _*_ coding:utf-8 _*_
d=dict(one=1,two=2,three=3)
print u'输出字典内容:'
print d
print u'查询字典中的内容:'
print d['one']
print d['three']
运算结果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
输出字典内容:
{'three': 3, 'two': 2, 'one': 1}
查询字典中的内容:
1
3
>>> 

二、字典的格式化字符串

# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3,'four':4}
print d
print "three is %(three)s." %d
运算结果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'four': 4, 'three': 3, 'two': 2, 'one': 1}
three is 3.
>>> 

三、字典方法 
3.1 clear函数:清除字典中的所有项

# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3,'four':4}
print d
d.clear()
print d
运算结果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'four': 4, 'three': 3, 'two': 2, 'one': 1}
{}
>>> 

请看下面两个例子 
3.1.1

# _*_ coding:utf-8 _*_
d={}
dd=d
d['one']=1
d['two']=2
print dd
d={}
print d
print dd
运算结果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'two': 2, 'one': 1}
{}
{'two': 2, 'one': 1}
>>> 

3.1.2

# _*_ coding:utf-8 _*_
d={}
dd=d
d['one']=1
d['two']=2
print dd
d.clear()
print d
print dd
运算结果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'two': 2, 'one': 1}
{}
{}
>>> 

3.1.2与3.1.1唯一不同的是在对字典d的清空处理上,3.1.1将d关联到一个新的空字典上,这种方式对字典dd是没有影响的,所以在字典d被置空后,字典dd里面的值仍旧没有变化。但是在3.1.2中clear方法清空字典d中的内容,clear是一个原地操作的方法,使得d中的内容全部被置空,这样dd所指向的空间也被置空。 
3.2 copy函数:返回一个具有相同键值的新字典

# _*_ coding:utf-8 _*_
x={'one':1,'two':2,'three':3,'test':['a','b','c']}
print u'初始X字典:'
print x
print u'X复制到Y:'
y=x.copy()
print u'Y字典:'
print y
y['three']=33
print u'修改Y中的值,观察输出:'
print y
print x
print u'删除Y中的值,观察输出'
y['test'].remove('c')
print y
print x
运算结果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
初始X字典:
{'test': ['a', 'b', 'c'], 'three': 3, 'two': 2, 'one': 1}
X复制到Y:
Y字典:
{'test': ['a', 'b', 'c'], 'one': 1, 'three': 3, 'two': 2}
修改Y中的值,观察输出:
{'test': ['a', 'b', 'c'], 'one': 1, 'three': 33, 'two': 2}
{'test': ['a', 'b', 'c'], 'three': 3, 'two': 2, 'one': 1}
删除Y中的值,观察输出
{'test': ['a', 'b'], 'one': 1, 'three': 33, 'two': 2}
{'test': ['a', 'b'], 'three': 3, 'two': 2, 'one': 1}
>>> 

注:在复制的副本中对值进行替换后,对原来的字典不产生影响,但是如果修改了副本,原始的字典也会被修改。deepcopy函数使用深复制,复制其包含所有的值,这个方法可以解决由于副本修改而使原始字典也变化的问题。

# _*_ coding:utf-8 _*_
from copy import deepcopy
x={}
x['test']=['a','b','c','d']
y=x.copy()
z=deepcopy(x)
print u'输出:'
print y
print z
print u'修改后输出:'
x['test'].append('e')
print y
print z
运算输出:
输出:
{'test': ['a', 'b', 'c', 'd']}
{'test': ['a', 'b', 'c', 'd']}
修改后输出:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'test': ['a', 'b', 'c', 'd', 'e']}
{'test': ['a', 'b', 'c', 'd']}
>>> 

3.3 fromkeys函数:使用给定的键建立新的字典,键默认对应的值为None

# _*_ coding:utf-8 _*_
d=dict.fromkeys(['one','two','three'])
print d
运算输出:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three': None, 'two': None, 'one': None}
>>> 

或者指定默认的对应值

# _*_ coding:utf-8 _*_
d=dict.fromkeys(['one','two','three'],'unknow')
print d
运算结果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three': 'unknow', 'two': 'unknow', 'one': 'unknow'}
>>> 

3.4 get函数:访问字典成员

# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3}
print d
print d.get('one')
print d.get('four')
运算结果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three': 3, 'two': 2, 'one': 1}
1
None
>>> 

注:get函数可以访问字典中不存在的键,当该键不存在是返回None 
3.5 has_key函数:检查字典中是否含有给出的键

# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3}
print d
print d.has_key('one')
print d.has_key('four')
运算结果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three': 3, 'two': 2, 'one': 1}
True
False
>>> 

3.6 items和iteritems函数:items将所有的字典项以列表方式返回,列表中项来自(键,值),iteritems与items作用相似,但是返回的是一个迭代器对象而不是列表

# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3}
print d
list=d.items()
for key,value in list:
    print key,':',value
运算结果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three': 3, 'two': 2, 'one': 1}
three : 3
two : 2
one : 1
>>> 
# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3}
print d
it=d.iteritems()
for k,v in it:
    print "d[%s]="%k,v
运算结果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three': 3, 'two': 2, 'one': 1}
d[three]= 3
d[two]= 2
d[one]= 1
>>> 

3.7 keys和iterkeys:keys将字典中的键以列表形式返回,iterkeys返回键的迭代器

# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3}
print d
print u'keys方法:'
list=d.keys()
print list
print u'\niterkeys方法:'
it=d.iterkeys()
for x in it:
    print x
运算结果:
{'three': 3, 'two': 2, 'one': 1}
keys方法:
['three', 'two', 'one']

iterkeys方法:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
three
two
one
>>> 

3.8 pop函数:删除字典中对应的键

# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3}
print d
d.pop('one')
print d
运算结果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three': 3, 'two': 2, 'one': 1}
{'three': 3, 'two': 2}
>>> 

3.9 popitem函数:移出字典中的项

# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3}
print d
d.popitem()
print d
运算结果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three': 3, 'two': 2, 'one': 1}
{'two': 2, 'one': 1}
>>> 

3.10 setdefault函数:类似于get方法,获取与给定键相关联的值,也可以在字典中不包含给定键的情况下设定相应的键值

# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3}
print d
print d.setdefault('one',1)
print d.setdefault('four',4)
print d
运算结果:
{'three': 3, 'two': 2, 'one': 1}
1
4
{'four': 4, 'three': 3, 'two': 2, 'one': 1}
>>> 

3.11 update函数:用一个字典更新另外一个字典

# _*_ coding:utf-8 _*_
d={
    'one':123,
    'two':2,
    'three':3
   }
print d
x={'one':1}
d.update(x)
print d
运算结果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three': 3, 'two': 2, 'one': 123}
{'three': 3, 'two': 2, 'one': 1}
>>> 

3.12 values和itervalues函数:values以列表的形式返回字典中的值,itervalues返回值得迭代器,由于在字典中值不是唯一的,所以列表中可以包含重复的元素

# _*_ coding:utf-8 _*_
d={
    'one':123,
    'two':2,
    'three':3,
    'test':2
   }
print d.values()
运算结果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
[2, 3, 2, 123]
>>> 

猜你喜欢

转载自blog.csdn.net/pansaky/article/details/81568318