字符串的拼接方法
(一)直接用“+”号,效率低(会在内存开辟另一块空间)
name = 'Jacky' + ' Zhao'
(二)字符串格式化
name = '%s %S' % ('Jacky','Zhao')
(三)join方法
listname = ['Jacky',' Zhao'] name = ''.join(listname)
(四)format格式化
name = 'jacky {0} {1} {2}' result = name.format('is','good','pepole') print(result) >>>jacky is good pepole
name = '{name} is a good {what}' result = name.format(name='Jacky',what='pepole') print(result) >>>Jacky is a good pepole
int内部功能
#相加 age = 18 age.__add__(7) #等于18 + 7 >>>25 #divmod 取商和余数(两种方法) age.__divmod__(7) #等于 18 // 7 和18 % 7 组成的元组,就是18 / 7的商和余数(左除右) >>>(2,4) age.__rdivmod__(7) #等于 7 // 18 和7 % 18 组成的元组,就是7 / 18的商和余数(右除左) >>>(0,7) #返回绝对值 age = -14 age__abs__() >>>14
str内部功能
#包含 name = 'jacky' result = name.__contains__('jac') #相当于 result = 'jac' in name print(result) >>>True result = name.__contains__('jac6') print(result) >>>False
#首字母变大写 name = 'jacky' result = name.capitalize() print(result) >>>Jacky #首字母变小写 name = 'Jacky' result = name.casefold() print(result) >>>jacky #字母全部变大写 name = 'jacky' result = name.swapcase() print(result) >>>JACKY #居中 name = 'jacky' result = name.center(20,'*') #50表示一共50个字符位,*号表示除字符串外的位用*号代替 print(result) >>>*******jacky******** #找字符串中的了序列出现的次数 file = 'alskjdhflakjsdhflasdfhlasdjfhl' a = file.count('d') print(a) >>>4 b = file.count('d',5,15) #表示从第5个起到第10个字符中d 出现的次数 print(b) >>>2 #转码 name = '小明' result = name.encode('gbk') #系统自动把字符串‘小明’的格式UTF8 转成unicode,再转成gbk print(result) >>>b'xd0xa1xc3xf7' #判断是不是以某个字符结尾的 name = 'jacky' result = name.endswith('ky') print(result) >>>True #把tab转移成空格,‘ ’表示tab name = 'j acky' result = name.expandtabs() print(result) >>>j acky #找字符串的的字符位置 name = 'jacky zhao' result = name.find('k') result0 = name.index('k') result1 = name.find('L') #find方法中,如果找不到就返回‘-1’ print(result,result0,result1) >>>3 3 -1 result2 = name.index('L') #index方法中,如果找到就返回‘报错:not found’ >>>result2 = name.index('L') ValueError: substring not found #字符转换 name = 'kbkbkbkbkbk' result = name.replace('k','b') #把‘k’全部转换成‘b’ print(result) >>>bbbbbbbbbbb name = 'kbkbkbkbkbk' result = name.replace('k','b',4) #把前4个‘k’转换成‘b’ print(result) >>>bbbbbbbbkbk
元组内部功能
#元组get取值 dic = {'k1':'v1','k2':'v2'} print(dic.get('k1')) >>>v1 print(dic.get('k2')) >>>v2 print(dic.get('k3')) #如果key不存在,显示none(默认值) >>>None print(dic.get('k3','jacky')) #如果key不存,传入的参数才能生效 >>>jacky print(dic.keys()) #获取所有的key值 >>>dict_keys(['k1', 'k2']) print(dic.values()) #获取所有的key的值 >>>dict_values(['v1', 'v2']) print(dic.items()) #获取所有的键值对 >>>dict_items([('k1', 'v1'), ('k2', 'v2')]) dic.pop('k1') #删除指定的键值对 print(dic) >>>{'k2': 'v2'}