two

模块引用

模块在文件头部引用一次即可生效,打印python全局环境变量

1
2
import sys
print(sys.path)

打印当前脚本路径

1
2
import sys
print(sys.argv)

列出文件夹中的文件信息,使用os.popen(command)可以直接调用系统命令

1
2
3
import os
cmd_dir = os.popen("dir").read()
print(cmd_dir)

创建文件夹

1
2
import os
os.mkdir("day3")

三元运算

如果 b < c 条件成立 d = 变量a的值,如果条件不成立 d = 变量c的值

1
2
3
a,b,c = 1,2,3
d = a if b < c else c
print(d)

字符类型转换

将字符串编码成字节包(Byte类型)

1
2
3
4
msg = "你好"
print(msg)
msg2 = msg.encode(encoding="utf-8")
print(msg2)

字节包解码为将字符串

1
2
msg3 = msg2.decode(encoding="utf-8")
print(msg3)

列表

打印列表

1
2
names = ["ZhangXiaoFan","LinJingYu","ZengShuShu","ZhouYiXian"]
print(names)

打印指定位置的姓名(第1个从0开始)

1
2
names = ["ZhangXiaoFan","LinJingYu","ZengShuShu","ZhouYiXian"]
print(names[2])

打印第二,第三个姓名(从0开始包含第1个,不包含第3个)

1
2
names = ["ZhangXiaoFan","LinJingYu","ZengShuShu","ZhouYiXian"]
print(names[1:3])

打印最后一个姓名

1
2
names = ["ZhangXiaoFan","LinJingYu","ZengShuShu","ZhouYiXian"]
print(names[-1])

打印最后两个

1
2
names = ["ZhangXiaoFan","LinJingYu","ZengShuShu","ZhouYiXian"]
print(names[-2:])

打印前三个

1
2
3
names = ["ZhangXiaoFan","LinJingYu","ZengShuShu","ZhouYiXian"]
print(names[0:3])
print(names[:3])

按照步长打印

1
2
names = ["ZhangXiaoFan","LinJingYu","ZengShuShu","ZhouYiXian","TianBuYi","CangSong","ZengShuChang"]
print(names[::2])

追加元素

追加到列表尾部

1
2
3
names = ["ZhangXiaoFan","LinJingYu","ZengShuShu","ZhouYiXian"]
names.append("XiaoYiCai")
print(names)

追加到指定位置

1
2
3
names = ["ZhangXiaoFan","LinJingYu","ZengShuShu","ZhouYiXian"]
names.insert(0,"XiaoYiCai")
print(names)

修改元素

1
2
3
names = ["ZhangXiaoFan","LinJingYu","ZengShuShu","ZhouYiXian"]
names[0] = "GuiLi"
print(names)

删除元素

删除指定元素名

1
2
3
names = ["ZhangXiaoFan","LinJingYu","ZengShuShu","ZhouYiXian"]
names.remove("ZhouYiXian")
print(names)

删除指定下标位置的元素(如果不指定参数默认删除最后一个)

1
2
3
4
5
names = ["ZhangXiaoFan","LinJingYu","ZengShuShu","ZhouYiXian"]
names.pop(2)
print(names)
names.pop()
print(names)

删除指定下标位置的元素

1
2
3
names = ["ZhangXiaoFan","LinJingYu","ZengShuShu","ZhouYiXian"]
del names[1]
print(names)

查找元素

通过元素名获取下标

1
2
3
names = ["ZhangXiaoFan","LinJingYu","ZengShuShu","ZhouYiXian"]
number = names.index("LinJingYu")
print(number)

通过下标获取元素名

1
2
3
names = ["ZhangXiaoFan","LinJingYu","ZengShuShu","ZhouYiXian"]
name = names[2]
print(name)

查找元素出现次数

1
2
3
names = ["ZhangXiaoFan","LinJingYu","ZengShuShu","ZhouYiXian","ZhangXiaoFan"]
count = names.count("ZhangXiaoFan")
print(count)

清空列表

1
2
3
names = ["ZhangXiaoFan","LinJingYu","ZengShuShu","ZhouYiXian","ZhangXiaoFan"]
names.clear()
print(names)

反转列表元素

1
2
3
4
names = ["ZhangXiaoFan","LinJingYu","ZengShuShu","ZhouYiXian"]
print(names)
names.reverse()
print(names)

元素排序

默认排序方式(特殊字符>数字>大写字母>小写字母)

1
2
3
names = ["ZhangXiaoFan","LinJingYu","zengShuShu","#ZhouYiXian","1ZhangXiaoFan"]
names.sort()
print(names)

列表合并

1
2
3
4
names = ["ZhangXiaoFan","LinJingYu","ZengShuShu"]
names2 = ["TianBuYi","CangSong","ZengShuChang"]
names.extend(names2)
print(names)

列表复制

列表复制(与普通变量复制不同列表中的复制等于两个列表指向同一个内存空间,其中一个值更改另一个会同步)

1
2
3
4
5
names = ["ZhangXiaoFan","LinJingYu","ZengShuShu"]
names2 = names
names[0] = "张小凡"
print(names2)
print(names)

浅copy直接复制一份变量到新的内存空间,源变量值更改不影响copy后的

1
2
3
4
5
names = ["ZhangXiaoFan","LinJingYu","ZengShuShu"]
names2 = names.copy()
names[0] = "张小凡"
print(names2)
print(names)

深copy引用其内存空间地址,源变量值更改会影响copyhou的

1
2
3
4
5
6
7
names = ["ZhangXiaoFan","LinJingYu",["TianBuYi","CangSong","ZengShuChang"],"ZengShuShu"]
names2 = names.copy()
print(names)
print(names2)
names[2][0] = "田不易"
print(names)
print(names2)

copy一份完全独立的列表

1
2
3
4
5
6
7
import copy
names = ["ZhangXiaoFan","LinJingYu",["TianBuYi","CangSong","ZengShuChang"],"ZengShuShu"]
names2 = copy.deepcopy(names)
names[0] = "张小凡"
names2[2][0] = "田不易"
print(names)
print(names2)

元组

只读列表(只允许查,切片)

1
2
3
names = ("ZengShuShu","ZhangXiaoFan","LinJingYu","TianBuYi","CangSong","ZengShuChang","ZengShuShu")
print(names.count("ZengShuShu"))
print(names.index("LinJingYu"))

购物车程序:

需求:

1.启动程序后,让用户输入工资,然后打印商品列表
2.允许用户根据商品编号购买商品
3.用户选择商品后,检测余额是否够,够就添加购物车扣款,否则提醒
4.可随时退出,退出时打印已经购买的商品和余额

实现方法:

1.创建两个列表商品列表,购物车列表
2.用户输入工资
    2.1.判断用户输入的工资是否是数字,如果是数字则转换为int类型否则退出并给出提示
3.循环打印商品列表
4.让用户输入购买的商品编号
    3.1.判断用户输入的是否是数字,并且商品编号中存在
    3.2.判断用户余额是否大于等于选择商品的价格,如果是则添加商品信息到购物车,扣除商品价格并给出提示
    3.3.判断如果用户输入的是q,则打印购物车列表,提示信息,余额;否则打印输入编号异常

code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# Author: Yi Xuan
product_list = [
('Iphone',5800),
('Mac Pro',9800),
('Which',10600),
('Starbuck Latte',31),
('Alex Python',120),
('Bike',800)
]
shopping_list = []
salary = input("请输入金额:")
if salary.isdigit():
salary = int(salary)
while True:
for index,item in enumerate(product_list):
print(index,'.',item[0],item[1])
user_choice = input('请输入需要购买的商品编号:')
if user_choice.isdigit():
user_choice = int(user_choice)
if user_choice < len(product_list) and user_choice >= 0:
p_item = product_list[user_choice]
if p_item[1] <= salary:
shopping_list.append(p_item)
salary -= p_item[1]
print('商品:%s 已经添加到购物车,当前余额为:%s' % (p_item,salary))
else:
print('商品购买失败...你的余额不足只剩下:%s' % salary)
else:
print('你输入的商品编号不存在....')
elif user_choice == 'q':
print('----------Shopping List----------')
for p in shopping_list:
print(p)
exit('你已经退出购物商城,当前余额为:%s' % salary)
else:
print('请输入正确的商品编号,或者输入q退出...')
else:
print('请输入数字...')

字符串处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
name = 'my name is\t Yi Xuan'
print(name.capitalize()) # 输出首字母大写
print(name.count('n')) # 统计name变量中字符'n'出现的次数
print(name.center(50,'#')) # 打印一行字符串长度50个字符串,长度不够两端用'#'填充
print(name.endswith('an')) # 判断字符串是否是'an'结尾(True;False)
print(name.expandtabs(tabsize=30)) # 设置name变量中\t的大小为30个字符串
print(name.find('n')) # 查找字符串下标
print(name[name.find('is'):]) # 打印变量中'is'开头到结尾的部分
print(name[:name.find('is')]) # 打印变量中开头到'is'结尾的部分

msg = 'my name is {name} number {number}'
print(msg.format(name='YiXuan',number=123456)) # 格式化输出
print(msg.format_map({'name':'YiXuan','number':123456})) # 使用字典传递参数
print('abc123'.isalnum()) # 字符串中是否包含'英文字母或数字(True/False)'
print('abc'.isalpha()) # 字符串是否是英文字母
print('1'.isdecimal()) # 字符串是否是十进制整数
print('_a'.isidentifier()) # 判断字符串是否是一个合法的变量名
print('asdfs'.islower()) # 判断字符串是否是小写
print('ABDS'.isupper()) # 判断字符串是否是大写
print('9'.isnumeric()) # 判断是否仅十进制数字
print(' '.isspace()) # 判断是否是空格
print('My Name Is'.istitle()) # 判断字符串中每个单词的首字母是否是大写
print('title'.center(50,'-')) # 打印字符串长度为50两端用符号'-'填充
print('title'.ljust(50,'-')) # 打印字符串长度为50右端用符号'-'填充
print('title'.rjust(50,'-')) # 打印字符串长度为50左端用符号'-'填充
print('10001'.zfill(8)) # 将字符串扩充到8位左侧使用0填充
print('title'.upper()) # 将字符串转换为大写
print('TITLE'.lower()) # 将字符串转换为小写
print('XiongJunFeng'.swapcase()) # 大小写反转
print(' hello world '.strip()) # 去除两端空格与换行
print(' hello world '.lstrip()) # 去除左端空格与换行
print(' hello world '.rstrip()) # 去除右端空格与换行
print('a b c d e f g h'.split()) # 默认按照空格将字符串转换为列表split()中可指定分割字符
print('a b c\nd e f g h'.splitlines()) # 按照换行符转换字符串为列表(由于windows/linux换行符不同此函数可实现自动转换)
print('+'.join(['1','2','3']))

# 字符替换
str = str.maketrans('abcdefghijklmnopqrstuvwxyz','1234567890-=_+`~!@#$%^&*()')
print('xiongjunfeng'.translate(str))

# 将字符串中的前两个`n`替换为指定参数(第三参数如果没有则代表替换全部的)
print('xiongjunfeng'.replace('n','N',2))

字典

1
2
3
4
5
6
7
8
9
10
11
12
# Author: Yi Xuan
info = {
'stu001':'Zhang Xiao Fan',
'stu002':'Lin Jing Yu',
'stu003':'Zeng Shu Shu',
'stu004':'Tian BuYi',
'stu005':'Cang Song',
'stu006':'Zeng Shu Chang',
}
print(info)
for i in info:
print(i ,'\t',info[i])