python常用方法

python常用方法

字符串

01.字符串常用方法

1.1 find方法
  • 作用:find方法可以在一个较长的字符串中查找子串,他返回子串所在位置的最左端索引,如果没有找到则返回-1
a = 'abcdefghijk'
print(a.find('abc'))                         #the result : 0
print(a.find('abc',10,100))                    #the result : 11  指定查找的起始和结束查找位置
1.2 join方法
  • 作用:join方法是非常重要的字符串方法,他是split方法的逆方法,用来连接序列中的元素,并且需要被连接的元素都必须是字符串。
a = ['1','2','3']
print('+'.join(a))                                    #the result : 1+2+3
1.3 split方法
  • 作用:这是一个非常重要的字符串,它是join的逆方法,用来将字符串分割成序列
print('1+2+3+4'.split('+'))                            #the result : ['1', '2', '3', '4']
1.4 strip
  • 作用:strip 方法返回去除首位空格(不包括内部)的字符串
print("   test   test    ".strip())                #the result :“test   test”
1.5 replace
  • 作用:replace方法返回某字符串所有匹配项均被替换之后得到字符串
print("This is a test".replace('is','is_test'))     #the result : This_test is_test a test
1.6 首字母大写
>>> s = 'aBdkndfkFFD'
>>> s.capitalize()
'Abdkndfkffd'
1.7 Pinyin 模块,将汉字转换成拼音
#! /usr/bin/env python
# -*- coding: utf-8 -*-
from xpinyin import Pinyin

while True:
    p = Pinyin()
    fullname = raw_input('name:').strip()
    fullname = fullname.decode('utf8')
    print fullname
    xin = fullname[0]
    ming = fullname[1:]
    name = ming + '.' + xin
    username = p.get_pinyin(name, '')
    print username
    print username + '@yiducloud.cn'

02.字符串格式化

2.1 使用百分号(%)字符串格式化
num = 100
print("%d to hex is %x" %(num, num))        #100 to hex is 64
print("%d to hex is %#x" %(num, num))       #100 to hex is 0x64
2.2 使用format字符串格式化
#1. 位置参数
print("{0} is {1} years old".format("tom", 28))            #tom is 28 years old
print("{} is {} years old".format("tom", 28))             #tom is 28 years old
print("Hi, {0}! {0} is {1} years old".format("tom", 28))      #Hi, tom! tom is 28 years old

#2. 关键字参数
print("{name} is {age} years old".format(name = "tom", age = 28))    #tom is 28 years old

#3. 下标参数
li = ["tom", 28]
print("{0[0]} is {0[1]} years old".format(li))          #tom is 28 years old

列表

01.列表常用方法

1.1 append
#1. append用于在列表末尾追加新的对象
a = [1,2,3]
a.append(4)                          #the result : [1, 2, 3, 4]
1.2 count
#2. count方法统计某个元素在列表中出现的次数
a = ['aa','bb','cc','aa','aa']
print(a.count('aa'))                 #the result : 3
1.3 extend
#3. extend方法可以在列表的末尾一次性追加另一个序列中的多个值
a = [1,2,3]
b = [4,5,6]
a.extend(b)                          #the result :[1, 2, 3, 4, 5, 6]
1.4 index
#4. index函数用于从列表中找出某个值第一个匹配项的索引位置
a = [1,2,3,1]
print(a.index(1))                   #the result : 0
1.5 insert
#5. insert方法用于将对象插入到列表中
a = [1,2,3]
a.insert(0,'aa')            #the result : ['aa', 1, 2, 3]
1.6 pop
#6. pop方法会移除列表中的一个元素(默认是最后一个),并且返回该元素的值
a = [1,2,3]
a.pop()                             #the result : [1, 2]
a.pop(0)
1.7 remove
#7. remove方法用于移除列表中某个值的第一个匹配项
a = ['aa','bb','cc','aa']
a.remove('aa')                      #the result : ['bb', 'cc', 'aa']
1.8 reverse
#8. reverse方法将列表中的元素反向存放
a = ['a','b','c']
a.reverse()                         #the result : ['c', 'b', 'a']
1.9 sort
#9. sort方法用于在原位置对列表进行排序,意味着改变原来的列表,让其中的元素按一定顺序排列
a = ['a','b','c',1,2,3]
a.sort()                           #the result :[1, 2, 3, 'a', 'b', 'c']
1.10 enumerate
li = [11,22,33,44,55,66]
for k,v in enumerate(li, 1):  # 1.代表 k 从哪个数字开始
    print(k,v)
'''
1 11
2 22
3 33
'''
1.11 range和xrange
  • 指定范围,生成指定的数字
  • 注:python3中的range类似python2中的xrange,比如a = range(1,4) : a返回的不是列表对象而是一个可迭代对象(<class ‘range’>)
#1、range根据start与stop指定的范围以及step设定的步长,生成一个序列:range([start,] stop[, step])
#2、xrange 用法与 range 完全相同,所不同的是生成的不是一个list对象,而是一个生成器
for i in range(1,10,2):
    print(i)
1.12 列表去空
# 法1:
filter(None, your_list)

# 法2:
while '' in your_list:
    your_list.remove('')

# 法3:
your_list = [x for x in your_list if x != '']

02.元祖

  • 元组定义:元组和列表一样,也是一种序列,唯一的不同是元组不能修改。
2.1 创建元组
#1. 创建元组
a = (1,2,3,4,5,6)
#2. 将列表转换成元组
tuple([1,2,3,4])                                    #the result : (1, 2, 3, 4)
2.2 列表和元组常用函数
方法作用
com(x,y)比较两个值
len(seq)返回序列的长度
list(seq)把序列转换成列表
max(args)返回序列或者参数集合中得最大值
min(args)返回序列或者参数集合中的最小值
reversed(seq)对序列进行反向迭代
sorted(seq)返回已经排列的包含seq 所有元素的列表

字典

01.字典常用方法

1.1 clear
  • 作用:clear方法清除字典中所有的项,这是一个原地操作,所以无返回值(或者说返回None)
d = {}
d['Tom']=8777             # 在字典中添加数据           
d['Jack']=9999    
print(d)                 #the result : {'Jack': 9999, 'Tom': 8777}
d.clear()
print(d)                #the result : {}
1.2 copy
  • 作用:copy方法返回一个具有相同 ”键-值” 对的新字典,而不是副本
d = {'Tom':8777,'Fly':6666}
a = d.copy()
a['Tom'] = '改变后的值'
print(d)                        #{'Fly': 6666, 'Tom': 8777}
print(a)                        #{'Fly': 6666, 'Tom': '改变后的值'}
1.3 fromkeys
  • 作用:fromkeys方法使用给定的键建立新的字典,每个键都对应一个默认的值None。
  • 首先建造一个空字典,然后调用它的fromkeys方法,建立另一个字典
print({}.fromkeys(['name','age']))         #the result : {'age': None, 'name': None}
1.4 get
  • 作用:get方法是个更宽松的访问字典项的方法,如果试图访问字典中不存在的项时不会报错仅会 返回:None
d = {'Tom':8777,'Jack':8888,'Fly':6666}
print(d.get('Tom'))                              #the result :     8777
print(d.get('not_exist'))                          #the result :     None
1.5 循环字典
d = {'Tom':8777,'Jack':8888,'Fly':6666}
# 方法1:
for k,v in d.items():
    print(k,v)
# 方法2
for k in d.values():
    print(k)
# 方法:3
for k in d.keys():
    print(k)
1.6 pop
  • 作用:pop方法用于获得对应与给定键的值,然后将这个”键-值”对从字典中移除
d = {'Tom':8777,'Jack':8888,'Fly':6666}
v = d.pop('Tom')
print(v)                    #8777
1.7 setdefault
  • 作用:setdefault方法在某种程度上类似于get方法,能够获得与给定键相关联的值
  • 除此之外,setdefault还能在字典中不含有给定键的情况下设定相应的键值
d = {'Tom':8777,'Jack':8888,'Fly':6666}
d.setdefault('Tom')                          #the result : 8777
print(d.setdefault('Test'))                     #the result : None
print(d)                                  #{'Fly': 6666, 'Jack': 8888, 'Tom': 8777, 'Test': None}
1.8 update
  • 作用:update方法可以利用一个字典项更新另一个字典,提供的字典中的项会被添加到旧的字典中,如有相同的键则会被覆盖
d = {'Tom':8777,'Jack':8888,'Fly':6666}
a = {'Tom':110,'Test':119}
d.update(a)
print(d)                        #the result :{'Fly': 6666, 'Test': 119, 'Jack': 8888, 'Tom': 110}
1.9 将两个列表组合成字典
keys = ['a', 'b']
values = [1, 2]
#1、zip生成字典
print(dict(zip(keys,values)))                              # {'a': 1, 'b': 2}
#2、for循环推倒字典
print({keys[i]: values[i] for i in range(len(keys))})              # {'a': 1, 'b': 2}

集合

01.集合

  • 集合作用
    • 去重
    • 取两个列表的交集
    • 取两个列表的并集
list_1 = [1,2,3,4,5,1,2]
#1、去重(去除list_1中重复元素1,2)
list_1 = set(list_1)                                #去重: {1, 2, 3, 4, 5}
print(list_1)
list_2 = set([4,5,6,7,8])

#2、交集(在list_1和list_2中都有的元素4,5)
print(list_1.intersection(list_2))                      #交集: {4, 5}

#3、并集(在list_1和list_2中的元素全部打印出来,重复元素仅打印一次)
print(list_1.union(list_2))                          #并集: {1, 2, 3, 4, 5, 6, 7, 8}

#4、差集
print(list_1.difference(list_2))                        #差集:在list_1中有在list_2中没有:   {1, 2, 3}
print(list_2.difference(list_1))                        #差集:在list_1中有在list_2中没有:   {8, 6, 7}

#5、子集
print(list_1.issubset(list_2))                          #子集:    False    List_1中的元素是否全部在list2中
#6、父集
print(list_1.issuperset(list_2))                        #父集:    False    List_1中是否包含list_2中的所有元素

#7、交集
print(list_1 & list_2)                                  #交集    {4, 5}

#8、union并集
print(list_1 | list_2)                                  #并集:  {1, 2, 3, 4, 5, 6, 7, 8}

#9、difference差集
print(list_1 - list_2)                                  #差集:    {1, 2, 3}

#10、在集合中添加一个元素999
list_1.add(999)
print(list_1)                                       #Add()方法:          {1, 2, 3, 4, 5, 999}

#11、删除集合中任意一个元素不会打印删除的值
list_1.pop()                                        #Pop()方法:            无返回值

#12、discard删除集合中的指定元素,如过没有则返回None
print(list_1.discard("ddd"))                            #Discard()方法:   删除指定的值,没有返回None
  • 4
    点赞
  • 44
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值