首页 > 技术文章 > python--基础数据的常用用法(三)

sunshinely 2021-05-31 20:00 原文

 几种数据类型的常用方法

 

一、字符串

切片
1、字符串的切片
print("hello"[1:3]) //el
print("hello-hi"[3:]) //lo-hi
split 和 join
print("hello-hi".split('-')) //['hello', 'hi']      split()函数会将切的片作为列表,如果是列表或字典需先转为字符串然后调用split()
print("hello-hi".split('-')[0]) //hello是字符串
print("".join("hello-hi".split('-'))) //hellohi

二、列表

list1.count(obj)   // 计算某个元素出现次数 list1.count(2)
1
list1.append(obj)    // 追加在后面   list1.append(2)
>>> list1
[1, 3, 4, 2]
list1.extend(seq)    //列表后追加一个seq >>> list1.extend([8,9])
>>> list1
[1, 3, 4, 2, 8, 9]
list1.index(obj)     //列表中找出某个值,第一个匹配项,索引中的位置 [1, 3, 4, 2, 8, 9]
>>> list1.index(4)
2
list1.insert(index,obj)    //将对象插入到列表中 list1.insert(2,100)
>>> list1
[1, 3, 100, 4, 2, 8, 9]
list1.pop(obj=lst[-1])    //移除列表中的某个元素,默认最后一个,并返回这个值

>>> list1.pop()
9

>>> list1.pop(2)
100

list1.remove(obj)    //移除列表中某个值的第一个匹配项 >>> list1.remove(8)
>>> list1
[1, 3, 4, 2]
list1.reverse()   // 反转列表中的元素,对本身进行操作,不可用新的list接收,接收的也是None list1.reverse()
>>> list1
[2, 4, 3, 1]
list1.sort([func])    //对列表元素排序,对本身进行操作,不可用新的list接收,接收的也是None list1.sort()
>>> list1
[1, 2, 3, 4]
三、五种数据类型共同点与不同点:
可用for循环遍历 字符串 列表 元组 集合 字典这5种数据类型均可
len()显示元素个数 字符串 列表 元组 集合 字典这5种数据类型均可
可变与不可变对象
可变对象:列表 集合 字典
不可变对象:字符串 元组
可添加元素类型
list中可以添加任何类型元素
字典的key只能是不可变元素,value可以是任何类型元素
元组中初始创建时候可以包含任何类型元素
集合add时只能添加不可变元素
获取元素方式
字符串 列表 元组都可以通过 名称[下标]获取单个元素内容
字典通过 名称[key]获取value值,或通过 名称.get(key)获取value值
集合因为无序无法获取单个元素值,只能遍历
四、各种数据类型转换
字符串与列表的转换
str ---> list
print(list("hello-hi")) //['h', 'e', 'l', 'l', 'o', '-', 'h', 'i'] 每个字符串切割
print("hello-hi".split("-")) //['hello', 'hi'] 根据需要切割
list ---> str
list=['hello', 'hi'] //里面元素必须都是str类型,不能有一个int list等其他类型
print("".join(list)) //hellolist
字符串与字典的转换
str ---> dict
string={"Content-Type":"application/x-www-form-urlencoded"}
dict1=eval(str)
type(dict1)
dict ---> str
dict={'code': 1, 'msg': '登录失败,请重试'}
st=str(dict)
字符串与元组的转换
str ---> tuple
tuple("aabbcc") //('a', 'a', 'b', 'b', 'c', 'c')
tuple ---> str //里面元素必须都是str类型,不能有一个int tuple等其他类型
print('-'.join(('a','b','88')))
 
总结的这些在实际场合中使用频率稍高,另外关于元组、字典、集合的使用下次附上~
欢迎下方留言,共同探讨~
 

推荐阅读