1. 程式人生 > >6、Python數據類型

6、Python數據類型

字符 pwd true 數據類型 rem 敏感字符 n) pen 修改

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數據類型