今日自学了一些python的字符和列表功能,分享一下
如果觉得不错麻烦来个左手边点赞 ^_^
字符
py_str = 'hello world!'
py_str.capitalize() # 开头第1个字符大写
'Hello world!'
py_str.title() # 以标题形式输出,第1个是大写
'Hello World!'
py_str.center(20) # 以20个字符空间,居中显示内容,其他空格
' hello world! '
py_str.center(20, '#') #以20个字符空间,居中显示内容,其他以#填满
'####hello world!####'
py_str.ljust(20, '*') #以20个字符空间,左边显示内容,其他以*填满
'hello world!********'
py_str.rjust(20, '*') #以20个字符空间,右边显示内容,其他以*填满
'********hello world!'
py_str.count('l') # 统计l出现的次数
3
py_str.count('lo') # 统计lo出现的次数
1
py_str.endswith('!') # 以!结尾吗?
True
py_str.endswith('d!') # 以d!结尾吗?
True
py_str.startswith('a') # 以a开头吗?
False
py_str.islower() # 判断字母都是小写的?其他字符不考虑
True
py_str.isupper() # 判断字母都是大写的?其他字符不考虑
False
'Hao123'.isdigit() # 判断所有字符都是数字吗?
False
'Hao123'.isalnum() # 判断所有字符都是字母数字?
True
' hello\t '.strip() # 去除两端空白字符,常用
'hello'
' hello\t '.lstrip() # 去除左端空白字符
'hello\t '
' hello\t '.rstrip() # 去除右端空白字符
' hello'
'how are you?'.split() # 分隔符对字符串进行切片
['how', 'are', 'you?']
'hello.tar.gz'.split('.') # 以.对字符串进行切片
['hello', 'tar', 'gz']
'.'.join(['hello', 'tar', 'gz']) # 以.作为分隔符,将.所有的元素合并成一个新的字符串
'hello.tar.gz'
列表
alist[0] = 10 # 修改下标0的项目为10
alist[1:3] = [20, 30] # 修改下标1-2的项目为20,30
alist[2:2] = [22, 24, 26, 28] #在下标2后添加22,24,26,28
alist.append(100) # 追加100到列表
alist.remove(24) # 删除第一个24
alist.index('bob') # 返回下标
blist = alist.copy() # 相当于blist = alist[:]
alist.insert(1, 15) # 向下标为1的位置插入数字15
alist.pop() # 默认弹出最后一项
alist.pop(2) # 弹出下标为2的项目
alist.pop(alist.index('bob')) #弹出下标为bob下标的项目
alist.sort() # 顺序排序
alist.reverse() #倒序排序
alist.count(20) # 统计20在列表中出现的次数
alist.clear() # 清空
alist.append('new') # 追加new到列表
alist.extend('new') # 追加n,e,w到列表
alist.extend(['hello', 'world', 'hehe']) #追加'hello', 'world', 'hehe’到列表
3522

被折叠的 条评论
为什么被折叠?



