1.流程控制值之for循环
循环:重复(按照某种规律的)做一件事情
while循环:可以循环一切事物
for循环:提供了一种手段,不依赖索引值
for 变量名(会拿到容器类元素的每一个值,没有就结束循环)in 容器类元素:
print(变量名)
it = [1,2,3,4]
for i in lt:
print(i)
dic = {'a':1,'b':2,'c':3}
count = 0
for i in dic: # 对于字典,for循环只能拿到KEY
# print(i,dic[i])
print(count)
count += 1
for i in range(50,101): # 顾头不顾尾
print(1)
for i in range(50,101,3): # 3表示步长
print(1)
for + break 终止循环
for i in range(50,101,3):
if i == 53:
break # 中断循环
printn(i)
for + cuntinue
for i in range(50,101,3):
if i == 3
continue # 跳出本次循环,不执行后面的代码
print(i)
for + else(仅作了解)
for i in range(50,101,3,)
if i == 1000
break
print(i)
esle:u
print('如果没有被break终就执行代码')
for循环嵌套
外层循环一次,内存循环所有
for i in range(3)
print(f'-----:{i}')
for j in range(2):
print(f'********:{j}')
for循环实现loding
import time
print('Loading',end='')
for i in range(6):
print('.',end='')
time.sleep(0.2)
1.数字的内置方法
整型
浮点型
字符串
列表
字典
元组
集合
布尔
1.1 整型 int
作用:年龄/id
定义:可以使用int()方法将纯数字的字符串转为十进制的整型
age = 19
print(type(age))
常用操作+内置方法:算术运算+比较运算
有序or无序(有索引就有序,无索引就无序)
可变or不可变(值变id不变叫可变,值变id变叫不可变)整数不可变
x = 10
print(id(x))
x += 1
print(id(x))
lt = [1,2,3]
print(id(lt))
lt.append(4)
prinit(lt)
print(id(lt))
1.2 浮点型(float)
用法:薪资、身高、体重
定义:可以使用float()方法将纯数字的字符串转为浮点数字
x = float('111')
print(x)
print(type(x))
常用操作+内置方法:算术运算+比较运算
存一个值or多个值:一个值
有序or无序:无有序or无序一说
salary = 3.3
print(f'first:{id(salary)}')
salary = 5.1
print(f'second:{id(salary)}')
可变or不可变:不可变数据类型
1.3字符串
用途:描述性质的东西,如人的名字、单个爱好、地址、国家等
定义:使用“,“”,‘’‘’‘’,“”“”包裹的一串字符
- u'unicode': unicode编码的字符串
- b'101': 二进制编码的字符串
- r' ': 原生字符串,也就是说' '这是普通的两个字符,并没有换行的意思
name = 'Bob' # name = str('Bob')
s1 = str(1.1)
s2 = str([1,2,3])
print(f's1:{s1},type:{type(s1)}')
print(f's2:{s2},type"{type(s2)}')
常规操作+内置方法:常用操作和内置方法
1.3.1优先掌握
1. 按索引取值
2. 切片
3. 长度len
4. 成员运算in|not in
5. 移除空白
6. 切分split
7. 循环
1.按索引取值(只可取不可变)
# str索引值
mag = 'hello Bob'
# 123456789 # 索引序号
print(f'索引为6:{mag[6]}')
print(f'索引为-3:{mag[-3]}')
2.切片(顾头不顾尾,步长)
# 索引切片
msg = 'hello Bob'
# 123456789 #索引序号
print(f'切片3——最后:{msg[3:]}')
print(f'切片3-8: {msg[3:8]}')
print(f'切片3-8,步长为2: {msg[3:8:2]}')
print(f'切片3-最后,步长为2: {msg[3::2]}')
3.长度len
msg = 'hello Bob'
print(len(msg))
4.成员运算in和not in
msg = 'my name is bob, bob handsome'
print(f"'bob' in msg:{'bob' in msg}") # True
5.移除空白
# str移除空白strip()
name = '&&&n ick'
print(f"name.strip('&'): {name.strip('&')}") # strip()默认为' '.并且不修改原值,新创建空间
print(f"name:{name}")
# strip()应用场景
pwd = input('password:') # 用户可能手抖输入空格
if pwd.stript() == '123':
print('密码输入成功')
print(f"'*-& nick+'.strip('*-& +'):{'*-& +'}")
6.切片split
# str切片split
info = 'nick:male:19'
info_list1 = info.split(':')
info_list2 = info.split(':',1)
print(f'info_list1:{info_list1}')
print(f'info_list2:{info_list2}')
7.循环
msg = 'hello nick'
for i in msg:
print(i)
1.3.2 需要掌握
-
lstrip&rstrip
-
lower&upper
-
startswith&endswith
-
rsplit
-
join
-
replace
-
isdigit
1.lstrip()和rstrip()
# str 之lstrip()和rstrip
name = '&&nickk&&'
print(f"nick.lstrip('&'): {name.lstrip('&')}")
print(f"nick.rstrip('&'): {name.rstrip('&')}")
2.lower()和upper()
# str之Lowe()和upper
name = 'Nick Chen'
print(f"name.upper(): {name.lower()}")
print(f"name.upper(): {name.upper()}")
3.startswith()和endswith()
# str之startswith()和endswith()
name = 'Nick Chen'
print(f"name.startswith('Nick'): {name.startswith('Nick')}")
print(f"name.endswith('chen'): {name.endswith('chen')}")
name.startswith('Nick'): True
name.endswith('chen'): False
4.rsplit()
# str之rsplit()
info = 'nick:male:19'
print(f"info.rsplit(':', 1): {info.rsplit(':', 1)}") # 从右开始切割
info.rsplit(':', 1): ['nick:male', '19']
5.join()
lis = [1,2,'19']
print(f"':'.join(lis): {':'.join(lis)}") # 报错,数字不可和字符串拼接
# str之join()
lis = ['nick', 'male', '19']
print(f"':'.join(lis): {':'.join(lis)}")
':'.join(lis): nick:male:19
6.replace()
# str值replace()
name = 'nick shuai'
print(f"name.replace('shuai','handsome'): {name.replace('shuai','handsome')}")
name.replace('shuai','handsome'): nick handsome
7.isdigit()
# str值isdigit()
salary = '111'
print(salary.isdigit()) # True
salary = '111.1'
print(salary.isdigit()) # False
1.3.3 其他操作
- find|rfind|index|rindex|count
- center|ljust|rjust|zfill
- expandtabs
- captalize|swapcase|title
- is系列
1.find()、rfind()、index()、rindex()、count()
# str之find()、rfind()、index()、rindex()、count()
msg = 'my name is tank, tank shi sb, hha'
print(f"msg.find('tank'): {msg.find('tank')}") # 找不到返回-1
print(f"msg.find('tank',0,3): {msg.find('tank',0,3)}")
print(f"msg.rfind('tank'): {msg.rfind('tank')}") # 找不到返回-1
print(f"msg.index('tank'): {msg.index('tank')}") # 找不到报错
print(f"msg.rindex('tank'): {msg.rindex('tank')}") # 找不到报错
print(f"msg.count('tank'): {msg.count('tank')}")
msg.find('tank'): 11
msg.find('tank',0,3): -1
msg.rfind('tank'): 17
msg.index('tank'): 11
msg.rindex('tank'): 17
msg.count('tank'): 2
2.center()、ljust()、rjust()、zfill()
# str之center()、ljust()、rjust()、zfill()
print(f"'info nick'.center(50,'*'): {'info nick'.center(50,'*')}")
print(f"'info nick'.ljust(50,'*'): {'info nick'.ljust(50,'*')}")
print(f"'info nick'.rjust(50,'*'): {'info nick'.rjust(50,'*')}")
print(f"'info nick'.zfill(50): {'info nick'.zfill(50)}") # 默认用0填充
'info nick'.center(50,'*'): ********************info nick*********************
'info nick'.ljust(50,'*'): info nick*****************************************
'info nick'.rjust(50,'*'): *****************************************info nick
'info nick'.zfill(50): 00000000000000000000000000000000000000000info nick
3.expandtabs()
# str之expandtabs()
print(f"a\tb\tc: %s"%('a b c ')) # 默认制表符8个空格
print(f"'a\tb\tc'.expandtabs(32): %s"%('a b c '.expandtabs(32)))
a b c: a b c
'a b c'.expandtabs(32): a b c
4.captalize()、swapcase()、title()
# str之captalize()、swapcase()、title()
name = 'nick handsome sWAPCASE'
print(f"name.capitalize(): {name.capitalize()}")
print(f"name.swapcase(): {name.swapcase()}") # 大小写互转
print(f"name.title(): {name.title()}")
name.capitalize(): Nick handsome swapcase
name.swapcase(): NICK HANDSOME Swapcase
name.title(): Nick Handsome Swapcase
5.is数字系列(只是为了告诉你,判断是否为数字时除了中文数字以后使用isdigit()即可)
- isdecimal(): 检查字符串是否值包含十进制字符,如果是返回True,否则返回False。
- isdigit(): 如果字符串只包含数字则返回True,否则返回False。
- isnumeric(): 如果字符串中只包含数字字符,则返回True,否则返回False。
num = "1" #unicode
num.isdigit() # True
num.isdecimal() # True
num.isnumeric() # True
num = "1" # 全角
num.isdigit() # True
num.isdecimal() # True
num.isnumeric() # True
num = b"1" # byte
num.isdigit() # True
num.isdecimal() # AttributeError 'bytes' object has no attribute 'isdecimal'
num.isnumeric() # AttributeError 'bytes' object has no attribute 'isnumeric'
num = "IV" # 罗马数字
num.isdigit() # True
num.isdecimal() # False
num.isnumeric() # True
num = "四" # 汉字
num.isdigit() # False
num.isdecimal() # False
num.isnumeric() # True
===================
isdigit()
True: Unicode数字,byte数字(单字节),全角数字(双字节),罗马数字
False: 汉字数字
Error: 无
isdecimal()
True: Unicode数字,全角数字(双字节)
False: 罗马数字,汉字数字
Error: byte数字(单字节)
isnumeric()
True: Unicode数字,全角数字(双字节),罗马数字,汉字数字
False: 无
Error: byte数字(单字节)
================
import unicodedata
unicodedata.digit("2") # 2
unicodedata.decimal("2") # 2
unicodedata.numeric("2") # 2.0
unicodedata.digit("2") # 2
unicodedata.decimal("2") # 2
unicodedata.numeric("2") # 2.0
unicodedata.digit(b"3") # TypeError: must be str, not bytes
unicodedata.decimal(b"3") # TypeError: must be str, not bytes
unicodedata.numeric(b"3") # TypeError: must be str, not bytes
unicodedata.digit("Ⅷ") # ValueError: not a digit
unicodedata.decimal("Ⅷ") # ValueError: not a decimal
unicodedata.numeric("Ⅷ") # 8.0
unicodedata.digit("四") # ValueError: not a digit
unicodedata.decimal("四") # ValueError: not a decimal
unicodedata.numeric("四") # 4.0
#"〇","零","一","壱","二","弐","三","参","四","五","六","七","八","九","十","廿","卅","卌","百","千","万","万","亿"
6.is其他
- isalnum(): 如果字符串至少有一个字符并且所有字符都是字母或数字则返回True,否则返回False。
- isalpha(): 如果字符串至少有一个字符并且所有字符都是字母则返回True,否则返回False。
- islower(): 如果字符串中只包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是小写,则返回True,否则返回False。
- isspace(): 如果字符串中只包含空白,则返回True,否则返回False
- isupper(): 如果字符串中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是大写,则返回True,否则返回False。
- istitle(): 如果字符串是标题类型的(见title()),则返回True,否则返回False。
4.存一个值or多个值:一个值
5.有序or无序:只要是有索引的,都是有序的,因此字符串是有序的。
name = 'nick'
print(f'first:{id(name)}')
name = 'nick handsome'
print(f'second:{id(name)}')
first:4377100160
second:4377841264
6.可变or不可变:不可变数据类型
1.4列表
用途:多个装备、多个爱好、多门课程、多个朋友
定义:[]内可以有多个任意类型的值,逗号分隔元素
# my_girl_friend = list(['jason','tank','sean'])
my_girl_friend = ['jason', 'tank', 'sean']
print(f"my_girl_friend: {my_girl_friend}")
# my_girl_friend: ['jason', 'tank', 'sean']
l = list('hello nick')
print(f"l: {l}")
# l: ['h', 'e', 'l', 'l', 'o', ' ', 'n', 'i', 'c', 'k']
1.4.1 优先掌握
-
按索引取值(正向取值+反向取值),即可存也可以取
-
切片
-
长度len
-
成员运算in 和 not in
-
追加append
-
删除del
-
循环
1.按索引取值(正向取值+反向取值),即可存也可以取
# list之索引取值
name_list = ['nick', 'jason', 'tank', 'sean']
name_list[0] = 'nick handsom'
# name_list[1000] = 'tank sb' # 报错
print(f"name_list[0]:{name_list[0]})
# name_list[0]: nick handsom
2.切片
# list之切片
name_list = ['nick', 'jason', 'tank', 'sean']
print(f"name_list[0:3:2]: {name_list[0:3:2]}")
# name_list[0:3:2]: ['nick', 'tank']
.长度
# list之长度
name_list = ['nick', 'jason', 'tank', 'sean']
print(f"len(name_list): {len(name_list)}")
# len(name_list): 4
4.成员运算in和not in
# list之成员运算in和not in
name_list = ['nick', 'jason', 'tank', 'sean']
print(f"'tank sb' in name_list: {'tank sb' in name_list}")
print(f"'nick handsome' not in name_list: {'nick handsome' not in name_list}")
# 'tank sb' in name_list: False
# 'nick handsome' not in name_list: True
5.追加值
# list之追加值
name_list = ['nick', 'jason', 'tank', 'sean']
name_list.append('tank sb')
print(f"name_list: {name_list}")
# name_list: ['nick', 'jason', 'tank', 'sean', 'tank sb']
6.删除
# list之删除
name_list = ['nick', 'jason', 'tank', 'sean']
del name_list[2]
print(f"name_list: {name_list}")
# name_list: ['nick', 'jason', 'sean']
7.循环
# list之循环
name_list = ['nick', 'jason', 'tank', 'sean']
for name in name_list:
print(name)
# nick
# jason
# tank
# sean
1.4.2 需要掌握
- insert
- pop
- remove
- count
- index
- clear
- copy
- extend
- reverse
- sort
1.insert() (插入)
# list之insert()
name_list = ['nick', 'jason', 'tank', 'sean']
name_list.insert(1, 'handsome')
print(f"name_list: {name_list}")
# name_list: ['nick', 'handsome', 'jason', 'tank', 'sean']
2.pop()(按照索引删除值)
# list之pop(),pop()默认删除最后一个元素
name_list = ['nick', 'jason', 'tank', 'sean']
print(f"name_list.pop(1): {name_list.pop(1)}")
print(f"name_list: {name_list}")
# name_list.pop(1): jason
# name_list: ['nick', 'tank', 'sean']
3.remove()(按照值删除)
# list之remove()
name_list = ['nick', 'jason', 'tank', 'sean']
print(f"name_list.remove('nick'): {name_list.remove('nick')}")
print(f"name_list: {name_list}")
# name_list.remove('nick'): None
# name_list: ['jason', 'tank', 'sean']
4.count()(计数)
# list之count()
name_list = ['nick', 'jason', 'tank', 'sean']
print(f"name_list.count('nick'): {name_list.count('nick')}")
# name_list.count('nick'): 1
5.index()
# list之index()
name_list = ['nick', 'jason', 'tank', 'sean']
print(f"name_list.index('nick'): {name_list.index('nick')}")
# name_list.index('nick'): 0
6.clear()
# list之clear()
name_list = ['nick', 'jason', 'tank', 'sean']
name_list.clear()
print(f"name_list: {name_list}")
# name_list: []
7.copy()
# list之copy()
name_list = ['nick', 'jason', 'tank', 'sean']
print(f"name_list.copy(): {name_list.copy()}")
# name_list.copy(): ['nick', 'jason', 'tank', 'sean']
8.extend()
# list之extend()
name_list = ['nick', 'jason', 'tank', 'sean']
name_list2 = ['nick handsome']
name_list.extend(name_list2)
print(f"name_list: {name_list}")
# name_list: ['nick', 'jason', 'tank', 'sean', 'nick handsome']
9.reverse()
# list之reverse()
name_list = ['nick', 'jason', 'tank', 'sean']
name_list.reverse()
print(f"name_list: {name_list}")
# name_list: ['sean', 'tank', 'jason', 'nick']
10.sort()
# list之sort(),使用sort列表的元素必须是同类型的
name_list = ['nick', 'jason', 'tank', 'sean']
name_list.sort()
print(f"name_list: {name_list}")
# name_list.sort(reverse=True)
print(f"name_list_reverse: {name_list}")
# name_list: ['jason', 'nick', 'sean', 'tank']
# name_list_reverse: ['tank', 'sean', 'nick', 'jason']
4.存一个值or多个值:多个值
5.有序or无序:有序
hobby_list = ['read', 'run', 'girl']
print(f'first:{id(hobby_list)}')
hobby_list[2] = ''
print(f'second:{id(hobby_list)}')
# first:4522187016
# second:4522187016
6.可变or不可变:可变数据类型
内置方法的原理
class SelfList(list):
def self_sort(self):
for i in range(len(self)): # [0,1,2,3,4,5]
for j in range(len(self)): # [0,1,2,3,4,5]
if self[i] < self[j]:
self[i], self[j] = self[j], self[i]
lt = SelfList([2, 0, 4, 3, 5])
lt.sort()
print(lt)