python的字符和列表功能

今日自学了一些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’到列表

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值