字符串列表常用操作
python字符串,列表,字典常用方法
字符串下标
str='asdfhjkl'
print(str[2])
#输出:
d
#字符串 : a s d f h j k l
#下标 : 0 1 2 3 4 5 6 7
#注: 字符串的下标从0开始
字符串切片
#切割符 : []
str='asdfhjkl'
print(str[0:3]) # 1
print(str[0:5:2]) # 2
print(str[0:-1:2]) # 3
print(str[5:1:-1]) # 4
# [0:3]
头:尾
# [0:5:2]
[头:尾:步长]
#输出
asd #1
adf # 2
adf # 3
jhfd # 4
find() 查找在字符串中的位置
str='hello world'
print(str.find('python'))
输出:
6
6 是python 在str字符串中出现的起始位置
count() 计算在字符串中出现的次数
str='hello world'
print(str.count('o'))
输出:
2
o在str字符串中出现了2次
replace() 替换字符串中的某个值
str='hello world'
print(str.replace('world','python'))
输出:
hello python
replace('要替换的值',''替换后的值')
upper() 将字符串中的小写字母转换成大写
str='hello world'
print(str.upper())
输出:
HELLO WORLD
lower() 将大写转换成小写
str='HELLO WORLD'
print(str.lower())
输出:
hello world
字符串反转
使用切片完成字符串反转
str='asdf'
print(str[::-1])
输出:
fdsa
列表的常用操作
python的列表比C语言数组的强大之处就在于他能存储不同的数据类型
append向列表中添加数据
list=[1,2,3,4,5]
list.append('2')
输出:
[1,2,3,4,5,6]
extend() 将一个列表中的多个值逐一添加到新列表中
x=[1,2,3]
list=[5,6]
x.extend(list)
print(x)
输出:
[1,2,3,5,6[]
insert() 在指定下标下加入数据
list=[1,23,4,5]
list.insert(1,10)
print(list)
输出:
[1,10,23,4,5]
在下标为1的地方添加了10
列表的查找
in : 如果存在为True, 否者为False
not in : 如果不存在为True, 否者为False
列表删除:
del : 根据下标进行删除
pop : 删除最后一个元素
remove : 根据元素的值进行删除
列表的排序
reverse() 倒叙 从大到小
sort() 正序 从小到大
list=[1,2,3,4,5]
print(list.reverse())
print(list.sort())
输出:
[5,4,3,2,1]
[1,2,3,4,5]