首页 > 代码库 > 6、Python数据类型

6、Python数据类型

a. 整数 int
- 创建
a = 123
a = int(123)
- 转换
age = "18"
new_age = int(age)
b. 布尔值
- 创建
a = True
b = False
- 转换
- 数字转换,只有0是False,其他True
- 字符串, 只有""是False,其他True
- 待续...

c. 字符串
- 创建
a = "alex"
a = str(‘alex‘)
- 转换
age = 19
new_age = str(age)
- 字符串的拼接
name = ‘alex‘
gender = ‘女‘
new_str = name + gender
print(new_str)

- 字符串格式化
# 占位符,
# name = ‘我叫李杰,性别:%s,我今年%s岁,我在说谎!‘
# new_str = name %(‘男‘,19,)
# print(new_str)

name = ‘我叫李杰,性别:%s,我今年%s岁,我在说谎!‘ %(‘男‘,19,)
print(name)

- 判断子序列是否在其中

content = "Alex 前几天去泰国玩姑娘,一不小心染上了病,他的内心活动是,真该多来几个"

if "前几天去" in content:
print(‘包含敏感字符‘)
else:
print(content)

- 移除空白
val = " alex "
print(val)
# new_val = val.strip() # 左右
# new_val = val.lstrip()# 左边
# new_val = val.rstrip() # 右边
# print(new_val)
- 分割
user_info = "alex sb123 9"
# v = user_info.split(‘|‘)
# v = user_info.split(‘|‘,1)
# v = user_info.rsplit(‘ ‘,1)
# print(v)
- 长度(字符)
val = "李杰sb"
v = len(val)
print(v)
- 索引
val = "李杰sb"
v = val[0]
print(v)

val = input(‘>>>‘)
i = 0
while i < len(val):
print(val[i])
i += 1
- 切片

name = ‘我叫李杰,性别我今年岁,我在说谎!‘
print(name[0])
print(name[0:2])
print(name[5:9])
print(name[5:])
print(name[5:-2])
print(name[-2:])

d. 列表
创建:
a = [‘alex‘,‘狗‘,‘eric‘,123]
a = list([‘alex‘,‘狗‘,‘eric‘,123])

in判断:

if ‘al‘ in a:
pass

if ‘al‘ in a[0]:
pass

索引:
val = a[0]

长度:
val = len(a)

切片:
a = [‘alex‘,‘狗‘,‘eric‘,123]
v = a[0::2]
print(v)

追加:
a = [‘alex‘,‘狗‘,‘eric‘,123]
a.append(‘xxoo‘)
print(a)
插入:
a = [‘alex‘,‘狗‘,‘eric‘,123]
a.insert(0,‘牛‘)
print(a)
删除:
a = [‘alex‘,‘eric‘,‘狗‘,‘eric‘,123]
# a.remove(‘eric‘)
del a[0]
print(a)

更新:
a = [‘alex‘,‘eric‘,‘狗‘,‘eric‘,123]
a[1] = ‘阿斯顿发送到‘
print(a)

For循环:
a = [‘alex‘,‘eric‘,‘狗‘,‘eric‘,123]
for item in a:
print(item)
# break
# continue

e. 字典操作
- 创建

v = {
‘name‘: ‘alex‘,
‘password‘: ‘123123‘
}

# 常用操作

# 索引获取值
# n = v[‘name‘]
# print(n)

# 增加,无,增加;有,修改
# v[‘age‘] = 19
# print(v)

# 删除
# del v[‘name‘]
# print(v)

# 循环
# for item in v.keys():
# print(item)
# for item in v.values():
# print(item)
# for key,val in v.items():
# print(key,val)


print(len(user_dict))

PS: 相互嵌套
user_dict = {
‘k1‘: ‘v1‘,
‘k2‘: {‘kk1‘:‘vv1‘,‘kk2‘:‘vv2‘},
‘k3‘: 123,
‘k4‘: [‘alex‘,‘eric‘,[‘a‘,‘b‘,‘c‘],‘李杰‘,{‘k11‘:‘vv1‘}],
}
user_dict[‘k4‘][2].append(‘123‘)
user_dict[‘k4‘][4][‘n‘] = ‘过啥龙‘


应用:

user_list = [
{‘name‘:‘alex‘,‘pwd‘:‘123123‘,‘times‘:1},
{‘name‘:‘eric‘,‘pwd‘:‘123123‘,‘times‘:1},
{‘name‘:‘tony‘,‘pwd‘:‘123123‘,‘times‘:1},
]
user = input(‘用户名:‘)
pwd = input(‘密码:‘)
for item in user_list:
if user == item[‘name‘] and pwd == item[‘pwd‘]:
print(‘登录成功‘)
break

6、Python数据类型