常见类型转换
字符串,列表,dict,元组
字符串(str),列表(list),dict,元组(tuple)
1.(常用)字符串转数字
int('1')
float('2.5')
2.dict转其他类型
student_dict = {'name':'小明','age':7,'sex':'male'}
print(str(student_dict))
print(tuple(student_dict)) # 转出来的是key值
print(tuple(student_dict.values())) # 转出来的是values值
print(list(student_dict))
print(list(student_dict.values()))
3.tuple转其他类型
tuple1 = (1,2,3)
print(str(tuple1))
print(list(tuple1))
不能转为字典
4.list转换成其他类型
list1 = [1,2,3,4]
print(tuple(list1))
print(str(tuple1))
不能转为字典
5.字符串转其他类型
(常用) eval(str) 参数是字符串,把这段字符串当作一条语句来执行
str1 = '[1,2,3,4]'
str2 = 'sprint("hello)'
print(eval(str1))
print(list(eval(str1)))
6.zip()
两个列表或元组压缩成一个新的结构
dict(zip(('a','b','c','d','e'),(1,2,3,4,5,)))
print()
7.isxxx判断(常用):
是的话返回True,假的话返回false
-检测字符串是否由字母组成
'a'.isalpha() >>> True
-检测字符串是否为空格
' '.isspace() >>> True
-检测字符串是否由数字组成
'1'.isdigit() >>> True
-检测字符串是否以字母开头(变量名)
'a4'.isidentifier() >>> True
-检测字符串中所有字母字符是否都是大写字母
'ABCVG'.isupper() >>> True
-判断字符串中所有字符是否都属于可见字符
'\n\tweh'.isprintable() >>> False
'qewgknopiu'.isprintable() >>> True
8.常用的搜索
count(sub) 参数为要搜索的字字符串,返回子串出现的次数,参数一是要搜索的字母,参数二从第几个字符开始搜索
'aqeaqhgaq'.count('aq',2) >>> 2
'aqeaqhgaq'.count('aq') >>> 3
判断字符串是否以某个字符串开头结尾
'ascb'.startswith('a') >>> True
'ascb'.endswith('cb') >>> True
9.(常用)find()查找子字符串是否出现过,是的话返回下标,注意没找到时返回-1
'xydfskf'.find('xy') >>> 0
'xydfskf'.find('aaa') >>> -1
'dfxyskf'.find('xy') >>> 2
10.(常用)index()跟find()类似,只是没查找到时返回异常,会报错
'xydfskf'.index('xy') >>> 0
11.替换
(常用)replace(old,new) old 为老的字符串 new 为新的字符串(替换为老的字符串)
'abcpjhoi'.replace('abc','xyz') >>> 'xyzpjhoi'
12.填充 fill
字符串两边填充,第一参数是填充后的长度,第二个参数填充的字符,可以用于居中打印
居中打印
' abc'.center(5,'_') >>> '_abc_'
' abc'.center(6,'_') >>> '_abc__'
左边或右边进行填充
'abc'.ljust(5,'_') >>> 'abc__' # 右边填充
'abc'.rjust(5,'_') >>> '__abc' # 左边填充