Python基础之内置方法
Posted michealjy
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python基础之内置方法相关的知识,希望对你有一定的参考价值。
字符串的内置方法
按索引取值
msg = 'hello world'
print(f'msg[6]: msg[6]')
print(f'msg[-3]: msg[-3]')
msg[6]: w
msg[-3]: r
切片(顾头不顾尾,步长)
msg = 'hello nick'
print(f'msg[3:]: msg[3:]')
print(f'msg[3:8]: msg[3:8]')
print(f'msg[3:8:2]): msg[3:8:2]')
print(f'msg[3::2]: msg[3::2]')
print(f'切片所有:msg[:]')
print(f'反转所有 msg[::-1]: msg[::-1]')
print(f'切片-5~-2: msg[-5:-2:1]')
print(f'切片-2~-5: msg[-2:-5:-1]')
msg[3:]: lo nick msg[3:8]: lo ni msg[3:8:2]): l i msg[3::2]: l ik 切片所有:hello nick 反转所有 msg[::-1]: kcin olleh 切片-5~-2: ni 切片-2~-5: cin
长度len
msg = 'hello nick'
print(len(msg))
10
成员运算
msg = 'my name is micheal, micheal is handsome'
print(f"'nick' in msg: 'nick' in msg")
print(f"'jason' not in msg: 'jason' not in msg")
print(f"not 'jason' in msg: not 'jason' in msg")
‘nick‘ in msg: False ‘jason‘ not in msg: True not ‘jason‘ in msg: True
移除两边空白strip
name = '&&&n ick'
print(f"name.strip('&'): name.strip('&')") #strip()默认为' ', 并且不修改原值,新创建空间
print(f'name: name')
#strip()应用场景
pwd = input('password: ') #用户可能会手抖输入空格
if pwd.strip() == '123':
print('密码输入成功')
print(f"'*-& nick'.strip('*-& nick'): '*-& nick'.strip('*-& ')")
name.strip(‘&‘): n ick name: &&&n ick password: 123 密码输入成功 ‘*-& nick‘.strip(‘*-& nick‘): nick
切分split
info = "nick:male:19"
info_list1 = info.split(':')
info_list2 = info.split(':', 1)
print(f'info_list1:info_list1')
print(f'info_list2:info_list2')
info_list1:[‘nick‘, ‘male‘, ‘19‘] info_list2:[‘nick‘, ‘male:19‘]
循环
msg = 'hello nick'
for i in msg:
print(i,end=' ')
h e l l o n i c k
lower&upper
name = 'Nick Chen'
print(f"name.upper(): name.upper()")
print(f"name.lower(): name.lower()")
name.upper(): NICK CHEN name.lower(): nick chen
startswith & endswith
name = 'Nick Chen'
print(f"name.startswith('Nick'): name.startswith('Nick')")
print(f'name.endswith('chen'): name.endswith('chen')')
name.startswith(‘Nick‘): True name.endswith(‘chen‘): False
replace
#str值replace()
name = 'nick shuai'
print(f"name.replace('shuai', 'handsome'): name.replace('shuai', 'handsome')")
name.replace(‘shuai‘, ‘handsome‘): nick handsome
join
lis = [1, 3, '13']
print(f"':'.join(lis): ':'.join(lis)") #报错,数字不可和字符串拼接
#str值join()
lis = ['nick', 'male', '19']
print(f"':'.join(lis): ':'.join(lis)")
‘:‘.join(lis): nick:male:19
isdigit
#str之isdigit()应用场景
age = input('age: ')
if age.isdigit():
age = int(age)
if age < 18:
print('小姐姐好')
else:
print('阿姨好’)
else:
print(f'你的年龄能是这个age?')
age: 12 小姐姐好
列表类型的内置方法
按索引取值(正反向取值同字符串)
切片(同字符串)
长度(同字符串)
成员运算(同字符串)
追加值
# list之追加值
name_list = ['nick', 'jason', 'tank', 'sean']
name_list.append('tank sb')
print(f"name_list: name_list")
name_list: [‘nick‘, ‘jason‘, ‘tank‘, ‘sean‘, ‘tank sb‘]
删除
list之删除
name_list = ['nick', 'jason', 'tank', 'sean']
del name_list[2]
print(f"name_list: name_list")
name_list: [‘nick‘, ‘jason‘, ‘sean‘]
循环(同字符串)
insert()
#list之insert
name_list = ['nick', 'jason', 'tank', 'sean']
name_list.insert(1, 'handsome')
print(f'name_list: name_list')
name_list: [‘nick‘, ‘handsome‘, ‘jason‘, ‘tank‘, ‘sean‘]
pop()
#list之pop(),pop()默认删除最后一个元素
name_list = ['nick', 'jason', 'tank', 'sean']
print(f'name_list.pop(1): name_list.pop(1)')
name_list.pop(1): jason
remove()
# list之remove()
name_list = 'nick', 'jason', 'tank', 'sean'
print(f'name_list.remove("nick"): name_list.remove("nick")')
name_list.remove("nick"): None
count()
#list之count()
name_liat = ['nick', 'jason', 'tank', 'sean']
print(f"name_list.count('nick'): name_list.count('nick')")
name_list.count(‘nick‘): 1
index()
#list之index()
name_list = ['nick', 'jason', 'tank', 'sean']
print(f"name_list.index('nick'): name_list.index('nick')")
name_list.index(‘nick‘): 0
extend()
#list之extend
name_list = ['nick', 'jason', 'tank', 'sean']
name_list2 = ['nick handsome']
name_list.extend(name_list2)
print(f"name_list: name_list")
name_list: [‘nick‘, ‘jason‘, ‘tank‘, ‘sean‘, ‘nick handsome‘]
reverse()
#list之reverse()
name_list = ['nick', 'jason', 'tank', 'sean']
name_list.reverse()
print(f"name_list: name_list")
name_list: [‘sean‘, ‘tank‘, ‘jason‘, ‘nick‘]
sort()
#list之sort(), 使用sort列表的元素必须是同类型的
name_list = ['nick', 'jason', 'tank', 'sean']
name_list.sort()
print(f"name_list: name_list")
name_list.sort(reverse = True)
print(f"name_list_reverse: name_list")
name_list: [‘jason‘, ‘nick‘, ‘sean‘, ‘tank‘] name_list_reverse: [‘tank‘, ‘sean‘, ‘nick‘, ‘jason‘]
字典类型内置方法
按key取值:可存可取
#dict之按key取值
dic = 'a': 1, 'b': 2
print(f"first dic['a']: dic['a']")
dic['a'] = 3 #可以对原值进行修改
print(f"second dic['a']: dic['a']")
first dic[‘a‘]: 1 second dic[‘a‘]: 3
长度len(与字符串类似)
成员运算(同字符串)
删除
# dic之删除del
dic = 'a': 1, 'b': 2
del dic['a']
print(f"dic.get('a'): dic.get('a')")
# dic之删除pop
dic = 'a': 1, 'b': 2
dic.pop('a') #指定元素删除
print(f"dic.pop('a'):dic.pop('a')")
print(f"dic.pop('b'):dic.pop('b')")
dic.get(‘a‘): None
dic.get(‘a‘): None
dic.pop(‘b‘): 2
items()
dic = 'a': 1, 'b': 2
print(f"dic.items(): dic.items()")
dic = ‘a‘: 1, ‘b‘: 2print(f"dic.items(): dic.items()")
循环
# dic之循环
# dic是无序的,但是python3采用了底层优化算法,所以看起来是有序的,但是python2中的字典是无序
dic = 'a': 1, 'b': 2, 'c': 3, 'd': 4
for k, v in dic.items():# items可以换成keys()、values()
print(k, v,end=' ')
dic = ‘a‘: 1, ‘b‘: 2, ‘c‘: 3, ‘d‘: 4for k, v in dic.items():# items可以换成keys()、values() print(k, v,end=‘ ‘)
get()
# dic之get()
dic = 'a': 1, 'b': 2
print(f"dic.get('a'): dic.get('a')")
print(f"dic.get('c'): dic.get('c')")
dic.get(‘a‘): 1
dic.get(‘c‘): None
update()
# dic之update()
dic1 = 'a': 1, 'b': 2
dic2 = 'c': 3
dic1.update(dic2)
print(f"dic1: dic1")
dic1: ‘a‘: 1, ‘b‘: 2, ‘c‘: 3
setdefault()
#dic之setdefault() 有指定key不会改变值,无指定key则改变值
dic = 'a': 1, 'b': 2
print(f"dic.setdefault('a'): dic.setdefault('a',3)")
print(f"dic: dic")
print(f"dic.setdefault('c'): dic.serdefault('c',3)")
print(f"dic: dic")
dic.setdefault(‘a‘): 1
dic: ‘a‘: 1, ‘b‘: 2
dic.setdefault(‘c‘): 3
dic: ‘a‘: 1, ‘b‘: 2, ‘c‘: 3
小练习
统计s = ‘hello tank tank say hello sb sb’
中每个单词的个数
s = 'hello tank tank say hello sb sb'
s_split = s.split()
dic = dict()
for i in s:
if i in dic:
dic[i] += 1
else:
dic[i] = 1
print(dic)
‘hello‘: 2, ‘tank‘: 2, ‘say‘: 1, ‘sb‘: 2
以上是关于Python基础之内置方法的主要内容,如果未能解决你的问题,请参考以下文章