数字
int # 将字符串转换为数字
a = "123"
b = int(a)
print(b)
字符串
replace # 将指定字符串替换为指定字符串
a1 = "123a123a123a" b1 = a1.replace("a","4",2) # 将字符串中的a替换成数字4,最后的2表示只替换前2个 print(b1)
输出结果:12341234123a
find # 从开始往后查找,再找到第一个之后,获取其所在位置
a = ("cabacbac") b = a.find("c",1) # 查找字符串中的c所在位置,1表示指定从第1位开始查找,如没有输入这个1则默认从0位开始 print(b)
输出结果:4 # 若查询不到结果,则返回-1
join # 将字符串中的每一个元素按照指定分隔符进行拼接
a = "123abc" b = "_".join(a) # 分隔符可以为空 print(b)
输出结果:1_2_3_a_b_c
strip # 移除指定字符串
a = "cabc123cbac" b = a.strip(c) # 只能够移除首尾的字符,中间的字符不能移除 print(b)
输出结果:bac123cba
startswith # 查看是否以什么什么开头
a = "cba123cba" b = a.startswith("c") # 查看赋值a当中的字符串是否以c开头,返回的结果为True,证明是以c开头的 print(b)
输出结果:True
split # 分割为指定个数
name = "alex alex alex" a = name.split() b = name.split("l",2) # 用L作为分隔符,2表示只对前两个L做分割 print(a)
输出结果:['alex', 'alex', 'alex'] print(b)
输出结果:['a', 'ex a', 'ex alex']
upper # 将字符串中所有字符都转换为大写
name = "alexa ALEXA alexa" v = name.upper() print(v)
输出结果:ALEXA ALEXA ALEXA # 不管大小写,全部转换成大写
lower # 将字符串中所有字符都转换为小写
name = "alexa ALEXA alexa" v = name.lower() print(v)
输出结果:alexa alexa alexa # 不管大小写,全部转换成小写
format # 格式化,将一个字符串中的占位符替换为指定的值
a = 'i am {0}, age {1}' # 0表示第0个字符,1表示第1个字符 v = a.format('alex',19) # alex为第0个字符,替换到0的位置,19为第1个字符,替换到1个位置 print(v)
输出结果:i am alex, age 19
列表
[] # 切片
fruit = ['apple','pear','grape','orange']
print(fruit[1]) # pear
print(fruit[1:3]) # ['pear', 'grape']
print(fruit[-1]) # orange
print(fruit[:2]) # ['apple', 'pear']
append # 追加
fruit = ['apple','pear','grape','orange']
fruit.append('peach')
print(fruit) #['apple', 'pear', 'grape', 'orange', 'peach'
remove\pop\del # 删除
fruit = ['apple','pear','grape','orange']
fruit.remove('peach') # 删除指定的
print(fruit) #['apple', 'pear', 'grape', 'orange']
fruit.pop() # 删除列表最后一个元素
print(fruit) #['apple', 'pear', 'grape']
del fruit[2] # 删除指定的索引
print(fruit) #['apple', 'pear']
insert # 插入
fruit = ['apple','pear','grape','orange']
fruit.insert(1,'grape') # 把‘grape’加入到索引为1的位置
print(fruit) #['apple', 'grape', 'pear']
extend # 扩展
fruit = ['apple','pear','grape','orange']
fruit1 = ['apple','orange']
fruit2 = ['pear','grape']
fruit1.extend(fruit2)
print(fruit1) #['apple', 'orange', 'pear', 'grape']
元祖 # 元素不能被修改
# 创建元组
fruit = ('apple','orange','grape')
# 常用功能
print(fruit.count('apple')) #1
print(fruit.index('orange')) #1
字典
get # 根据Key获取值,key不存在时,可以指定默认值(None)
dic = {"k1": 'v1',"k2": 'v2'}
v = dic.get('k1',111111)
print(v)
update # 更新
dic = {"k1": 'v1', "k2": 'v2' }
dic.update({'k1': '111111','k3': 123})
print(dic)
dic.update(k1=123,k3=345,k5="asdf")
print(dic)
keys/values/items # for循环时输出不同结果
info = {
"k1": 99,
2: True,
"k3": {
'kk1': 'vv1',
'kk2': 'vv2',
'kk3': (11,22),
}
}
for item in info.keys():
print(item)
# 输出结果:
k1
2
k3
for item in info.values():
print(item)
# 输出结果:
99
True
{'kk1': 'vv1', 'kk2': 'vv2', 'kk3': (11, 22)}
for k,v in info.items():
print(k,v)
# 输出结果:
k1 99
2 True
k3 {'kk1': 'vv1', 'kk2': 'vv2', 'kk3': (11, 22)}