Python 基础篇:字符串、列表操作

时间:2022-11-22 16:36:56

字符串操作

判断是否为数字
string = "200"
string.isdigit()
>>false 待完善。。

列表操作

列表是我们最以后最常用的数据类型之一,通过列表可以对数据实现最方便的存储、修改等操作

定义列表:

names = ['warkly','kaliy','walkly','json']

通过下标访问列表中的元素,下标从0开始计数

names[0]
>>'warkly' names[1]
>>'kaliy' names[-1]
>>'json' names[-2]
>>'walkly'

1. 切片

取多个元素(顾头不顾尾)

names = ['warkly','kaliy','walkly','json']

names[1:2]
>>['kaliy','walkly'] names[0:2]
>>['warkly','kaliy','walkly'] names[:2] 等同上面,从开头取
>>['warkly','kaliy','walkly'] names[1:] 取到结尾
>>['kaliy','walkly','json'] names[0:2:3] ‘2’代表步长,每隔两个取一个
>>['warkly','json'] names[0::3] 默认步长是‘1’
>>['warkly','kaliy','walkly','json']

2. 追加

names = ['warkly','kaliy','walkly','json']

names.append("kevin")
names
>>['warkly','kaliy','walkly','json','kevin']

3. 插入

names = ['warkly','kaliy','walkly','json']

names.insert(2,"hellen")
names
>>['warkly','kaliy','hellen','walkly','json']

4. 修改

names = ['warkly','kaliy','walkly','json']

names[2] = 'kerry'
names
>>['warkly','kaliy','kerry','json']

5. 删除

names = ['warkly','kaliy','walkly','json']

del names[2]
names
>>['warkly','kaliy','json'] names.remove("walkly") 删除指定元素
names
>>['warkly','kaliy','json'] names.pop() 默认删除列表最后一个值
names
>>['warkly','kaliy','walkly']

6. 扩展

names = ['warkly','kaliy','walkly','json']
num = [1,2,3] names.extend(num)
names
>>['warkly','kaliy','walkly','json',1,2,3]

7. 拷贝

names = ['warkly','kaliy','walkly','json']

names_copy=names.copy()
names_copy
>>['warkly','kaliy','walkly','json']

8. 统计

names = ['warkly','kaliy','walkly','json',1,2,3]

names.count('json')
>>1

9. 排序与翻转

names = ['warkly','kaliy','walkly','json',1,2,3]

names.sort()
names
>>[1,2,3,'json','kaliy','walkly','warkly'] names.reverse()
names
>>[3,2,1,'json','walkly','kaliy','warkly']

10. 获取下标

names = ['warkly','kaliy','walkly','json',1,2,3]

names.index("kaliy")
>>1