字符串、列表、元组和字典
目录
1.字符串构造
单引号、双引号
三引号:多行显示
2.索引与切片
字符串属于序列,序列即有序排列
(1)正向单索引:——>,string[index],从0开始
负向单索引:str[-1],从-1开始
#转换类型:int、float、str、bool、strptime(转日期)//datetime.datetime.strptime('','%Y-%m-%d').date()
(2)有限切片:str[start:end]
无限切片:str[::step]
正向切片:string[:5],从0开始,不包括最后一个数字
3.字符串方法
(1)查询:
str.index(str[,start[,end]])
str.find(str[,start[,end]])
price='100元/斤'
#查询“元”所在位置
print(price.index('元'))
#应用总结:取出价格,并转换为浮点型数字
print(float(price[:price.index('元')]))
(2)压缩:(删除)
str.lstrip([])左删
str.rstrip([])右删
str.strip([])
m=' ^-^apple pen@@@ '
print(m.rstrip())
print(m.lstrip())
print(m.strip())
print(m.strip('^-^@'))
print(m.strip('@'))
x='&&&很棒!答对了!(^-^)'
print(x.strip('&(^-^)'))
#结果:
^-^apple pen@@@
^-^apple pen@@@
^-^apple pen@@@
^-^apple pen@@@
^-^apple pen@@@
很棒!答对了!
(3)替换:
str.replace(old,new)
phone='11155553336'
print(phone.replace(phone[3:7],'xxxx'))
#111xxxx3336
(4)格式化输出:
str.format()
ming='peter'
p=100.05
print('你好,{}先生,你本次充值{:.1f}元,实际到账{}元'.format(ming,p,p))
#你好,peter先生,你本次充值100.0元,实际到账100.05元
(5)分割:
str.split(sep)#sep是分割符
emmmm='1564@.com'
print(emmmm.split('@'))
ins='姓名|10岁|电话'
y=ins.split('|')[1]
print(float(y.strip()[:-1]))
# ['1564', '.com']
# 10.0
(6)其余方法:
待使用时扩展
4.其他容器
[列表]
可变是可变对象
列表元素的增加:
append列表末尾增加 一个元素
extend列表末尾可以增加多个元素
list=['1','100','789','890']
list.append('5')
print(list)
list.extend(['1','9'])
print(list)
print(list.count('1'))#元素频数
print(list.index('100'))#查询元素首次出现位置
list.sort()
#列表排序,必须同类型元素
print(list)
#['1', '100', '789', '890', '5']
#['1', '100', '789', '890', '5', '1', '9']
#2
#1
#['1', '1', '100', '5', '789', '890', '9']
(元组)
1.不可变对象
2.只包含一个元素时,用(123,)区分开
{字典}
字典元素以键值对的形式出现,键是唯一的,Key:Value,元素是没有顺序的
相比较于字符串、列表、元组,字典不再是序列,用键索引和get方法
字典的获取、增加和修改,都用[]的形式
dict={'name':'Mike','年龄':'50'}
print(dict['年龄'])
dict['年龄']=60
print(dict['年龄'])
#50
#60