用于表示文本等一些信息
name = "小空空"
v1 = len(name)
print(v)
name = "小空空"
name[0]
name[1]
name[2]
疑问:是否可以通过索引去修改字符串中的某个字符?不可以。
字符串底层存储时,是一个整体不允许被修改(原子)。
“小空空”去存储时会是一个了连续的地址空间:01001001001010 0100010010101010 1001001111100101,如果修改“小唔唔空”
name = "沈清欢"
v1 = name[0:2] # 沈清
注意:在索引和切片时,会存在负值和空的情况。
msg = "北京昌平沙河"
msg[0:6:1] # "北京昌平沙河"
msg[0:6:2] # "北昌沙"
msg[0:6:3] # "北平"
msg[::-1] # 河沙平昌京北
msg[-1::-1] # 河沙平昌京北
msg[-2::-1] # 沙平昌京北
msg[-2:0:-1] # 沙平昌京
msg[-2:1:-1] # 沙平昌
msg[5:0:-1] # '河沙平昌京'
msg[0:6:-1] # 空
msg[5:-1:-1] # 空
面试题:请将一个字符串进行反转。
name = "中华人民共和国"
方式一:name[::-1]
方式二:循环倒序展示
index = len(name)-1 # 注意 索引起点为 0 ,而len 长度计数 1 开始
while index >= 0:
name[index]
index -= 1
# IndexError: string index out of range
自动帮我们获取一个值内部的所有的数据(内部是基于索引完成)
name = "中华人民共和国"
# 方式一
index = 0
while index < len(name):
print(name[index])
index += 1
# 方式二
for item in name:
print(item)
注意: 在for循环中支持 break 和 continue
range,是Python中内部帮我们提供的一个函数,他可以帮我们生成整型的数据。
- range(8) # 0 1 2 3 4 5 6 7
- range(99) # 0 1 2 ... 98
- range(1,5) # 1 2 3 4
- range(1,5,2) # 1 3
- range(5,1,-1) # 5 4 3 2
- range(5,0,-1) # 5 4 3 2 1
在Python2中:
- range(1000000000000),在内存中帮我们立即创建1000000000000个整数。
- xrange(1000000000000),不会再内存中立即创建,而是在我们对xrange生成的结果进行for循环获取时,才会获取一个生成一起。
在python3中:
- range(1000000000000),不会再内存中立即创建,而是在我们对range生成的结果进行for循环获取时,才会获取一个生成一起。
# 示例代码
data = range(10)
print(data) # 此时没有生成 0 1 2 3 4 。。。
for item in data:
print(item)
# 1. 输出 1 ~ 100 内所有的整数。
v1 = range(1,101)
for i in v1:
print(i)
简写
for i in range(1,101):
print(i)
# 2. 输出一个字符串中的每个字符
name = "中华人民共和国"
for char in name:
print(char)
# 2. 输出一个字符串中的每个字符以及字符所在的索引位置。
name = "中华人民共和国"
for index in range(0,len(name)):
print(index,name[index]) # 0 1 2 3 4 5 6
请帮我生成一个随机验证码,随机验证码共6位且只包含字母(含大小写)。
- 循环6次
for index in range(6):
pass
- 每次生成1个字符,字符拼接起来。
code = ""
for index in range(6):
code = code + 随机字符 // code += 随机字符串
- 生成随机整数
import random
result = random.randint(0,3) # 0 ~ 3
print(result)
- 生成随机字符
import random
num = random.randint(65,90)
char = chr(num)
# 只有大写
import random
code = ""
for i in range(6):
num = random.randint(65,90)
char = chr(num)
code = code + char
print(code)
# 含大小写
import random
code = ""
for i in range(6):
temp = random.randint(0, 1)
if temp == 0:
num = random.randint(65, 90) # 随机 97 - 122
else:
num = random.randint(97, 122)
char = chr(num)
code = code + char
print(code)
# 扩展:项目中真用到了生成验证码的功能。
import random
import string
code = ""
all_letters = string.ascii_letters + string.digits
for i in range(6):
char = random.choice(all_letters)
code += char
print(code)
需求:有以下四个变量,分别是IP的四部分 "255.127.235.99",请将如下四个变量转换成为二进制并拼接起来,最后将拼接起来的二进制转换为十进制整数。
v1 = 18
v2 = 127
v3 = 235
v4 = 99
data = bin(v1) + bin(v2) + bin(v3) + bin(v4)
"0b10010" + 0b10010 + 0b10010 + 0b10010 => 第一步:将b去掉
"00010010" + 。。。 => 第二步:统一用8位二进制表示。
print(data) # 32位的一个二进制 "000100100001001000010010000100100001001000010010" => 十进制
result = ""
ip_list = [18,127,235,99]
for v in ip_list:
# print(v) # 18 127 235 99 # 转换二进制 -> 去掉b -> 凑够8位 ==》 字符串
part = bin(v)[2:]
if len(part) < 8:
part = ( 8 - len(part) ) * "0" + part
# print(part,len(part))
result = result + part
value = int(result,base=2)
print(value)
name = "alex"
data = name.startswith("al")
name = "alex"
data = name.endswith("ex")
name = "alex"
data = name.upper() # ALEX
age = "18"
data = age.isdecimal() # True
name = "alex"
data = name.replace('l','A')
name = " alex\t"
print(name,len(name))
# 默认去除前后的 空格、换行、制表符,得到一个新的字符串。
data = name.strip()
print(data,len(data))
name = "alex"
print(name,len(name))
# 去除前后的 x,得到一个新的字符串。
data = name.strip("x")
print(data,len(data))
lstrip,只去除左边
rstrip,只去除右边
v1 = "我叫{0},我今年{1}岁, 我的名字叫{0}".format("alex",73)
print(v1)
v2 = "我叫{name},我今年{age}岁, 我的名字叫{name}".format(name="alex",age=73)
print(v2)
name = "alex"
v1 = name.ljust(8,"*")
print(v1) # alex**** 字符串8位长度,不够的字符在左,右边补齐
v2 = name.rjust(8,"*")
print(v2) # ****
part = "10010"
part = part.rjust(8,"0")
print(part) # 00010010
ip = "192.168.1.1"
data = ip.split(".")
print(data) # ['192', '168', '1', '1'] => 列表
ip = "192.168.1.1"
v1 = ip.split(".") # ['192', '168', '1', '1']
v2 = ip.split(".",1) # ['192', '168.1.1']
path = "/Users/wupeiqi/project/s29day03/1.字符串反转.py"
v3 = path.rsplit(".") # ['/Users/wupeiqi/project/s29day03/1', '字符串反转', 'py']
v4 = path.rsplit(".",1) # ['/Users/wupeiqi/project/s29day03/1.字符串反转', 'py']
注意:split返回的是一个列表类型(内部元素都是字符串类型),列表可以被for循环。
data = "*".join(["alex","eric","tony"]) # "alex*eric*tony"
hobby = ["篮球","足球","乒乓球"]
data = ",".join(hobby) # "篮球,足球,乒乓球"
summary = "我叫alex,我的爱好有{0}。".formt(data)
print(summary) # 我叫alex,我的爱好有篮球,足球,乒乓球。
# summary = "我叫alex,我的爱好有{0}。".formt("足球") # 我叫alex,我的爱好有足球。
# summary = "我叫alex,我的爱好有{0}。".formt("篮球,足球,乒乓球") # 我叫alex,我的爱好有篮球,足球,乒乓球。
# 在之前,验证码和IP地址转换时都有字符串相加的操作(基于+),反复的这种相加效率非常差。
# 在之后,基于join和列表完成字符串的拼接。
# 例1:
result = [] # ["10001011","10000000","1111110","11001101"]
ip = "10.3.9.12"
data_list = ip.split(".") # ["10","3","9","12"]
for item in data_list:
# "10","3","9","12"
num = int(item)
temp = bin(num)[2:]
char = temp.rjust(8,"0")
result.append(char) # ["10001011","10000000","1111110","11001101"]
value = "".join(result)
print( int(value,base=2) )
# 例2:
import random
import string
data_list = [] # ["A","1","F","a","b","u"]
all_letters = string.ascii_letters + string.digits
for i in range(6):
char = random.choice(all_letters)
data_list.append(char)
code = "".join(data_list)
print(code) # A1Fabu
data = input("请输入数据:")
result = data.split("+") # ["5","99"]
# result[0] # 5
# result[1] # 99
value = int(result[0]) + int(result[1])
print(value)
data = input("请输入数据:")
result = data.split("+") # ["5","alex"]
if result[0].isdecimal() and result[1].isdecimal():
value = int(result[0]) + int(result[1])
print(value)
else:
print("输入有错误")
data = input("请输入数据:") # 5+99 、5 + 99 、 5+ 99
result = data.split("+") # ["5"," 99 "]
v1 = result[0].strip()
v2 = result[1].strip()
value = int(result[0]) + int(result[1])
如 "10.3.9.12" 转换规则为:
10 00001010
3 00000011
9 00001001
12 00001100
再将以上二进制拼接起来计算十进制结果:00001010 00000011 00001001 00001100 = ?
result = ""
ip = "10.3.9.12"
data_list = ip.split(".") # ["10","3","9","12"]
for item in data_list:
# "10","3","9","12"
num = int(item)
temp = bin(num)[2:]
char = temp.rjust(8,"0")
result += char
print(result)
print( int(result,base=2) )
列表是一个 有序 的容器,当我们在程序中想要表示多个数据时,都可以使用列表
v1 = [ 1, "alex", 2, True, 3.14 ]
例如:
users = ["alex","李杰","老男孩"]
email_list = ["[email protected]","[email protected]"]
users = [ "alex", "李杰", "老男孩"]
data = len(users)
users = [ "alex", "李杰", "老男孩"]
users[0] # "alex"
users[1] # "李杰"
uesrs[2] # "老男孩"
users[1] = "武沛齐"
print(users) # [ "alex", "武沛齐", "老男孩"]
users = [ "alex", "李杰", "老男孩"]
print(users) # ['alex', '李杰', '老男孩']
del users[1]
print(users) # ['alex', '老男孩']
# 基于while循环输入列表中的每个元素
users = [ "alex", "李杰", "老男孩"]
index = 0
while index < len(users):
print( users[index] )
index += 1
users = [ "alex", "李杰", "老男孩"]
users[0:2] # ["alex", "李杰"]
users[1:] # ["李杰","老男孩"]
users = [ "alex", "李杰", "老男孩"]
print(users) # ['alex', '李杰', '老男孩']
users[0:2] = ["wupeiqi","武沛齐","张扬","老妖"]
print(users) # ['wupeiqi', '武沛齐', '张扬', '老妖', '老男孩']
users = [ "alex", "李杰", "老男孩"]
print(users)
del users[0:2]
print(users)
users = [ "alex", "李杰", "老男孩"]
users[0:2:1]
users[0:2:2]
users[-1::-1]
users = [ "alex", "李杰", "老男孩"]
for item in users:
print(item)
users = [ "alex", "李杰", "老男孩"]
for i in range(len(users)):
# i=0,1,2
# users[i]
print(i, users[i] )
1、写代码,有如下列表,按照要求实现每一个功能
li = ["alex", "WuSir", "ritian", "barry", "wenzhou"]
print( len(li) )
li[::2]
li[1] = "kelly"
print(li)
del li[1]
del li[1:4]
li = [1, 3, 2, "a", 4, "b", 5,"c"]
li[0:3]
li[3:6]
li[::2]
li[1:6:2]
li[1::2]
li[-1]
li[-1:]
-通过对li列表的切片形成新的列表 [“b”,”a”,3]
li[-3:0:-2]
3、购物车
goods = ["电脑", "鼠标", "键盘"]
for i in range(len(goods)):
print(i, goods[i])
num = input("请选择商品:")
if num.isdecimal():
num = int(num)
if num < len(goods) and num >= 0:
print(goods[num])
else:
print("范围选择有误")
else:
print("请输入整数")
data_list = []
data_list.append("alex")
print(data_list) # ["alex" ]
data_list.append("武沛齐")
print(data_list) # ["alex","武沛齐" ]
goods = ["电脑", "鼠标", "键盘"]
print(goods)
goods.extend(["硬盘","读卡器","充电器"])
print(goods)
goods = ["电脑", "鼠标", "键盘"]
for item in ["硬盘","读卡器","充电器"]:
goods.append(item)
print(goods)
names = ["alex","日天","老男孩"]
names.insert(0,"苑昊") # 在第0个位置插入苑昊,结果:["苑昊","alex","日天","老男孩"]
print(names) # ["苑昊","alex","日天","老男孩"]
names = ["alex","日天","老男孩"]
# 根据索引删除
# del names[1]
names = ["alex","日天","老男孩"]
# 根据值删除
# names.remove("日天")
# print(names)
names = ["alex","日天","老男孩"]
# 根据值删除
# names.remove("日天")
# print(names)
l1 = ['a','a']
l1.remove('a')
print(l1)
# a
# 根据索引删除并获取删除的那个值,如果pop() 则默认删除列表的最后一个值。
# data = names.pop(0)
# print(names,data)
li1 = [0, 1, 'a', 2, 'a', 'a', 'b', 3, 4, 'b']
res1 = [x for x in li1 if x != 'a']
print(res1)
# [0, 1, 2, 'b', 3, 4, 'b']
li1 = [0, 1, 'a', 2, 'a', 'a', 'b', 3, 4, 'b'])
deleteList = ['a', 'b']
res2 = [x for x in li1 if x not in deleteList]
print(res2)
# [0, 1, 2, 3, 4]
names = ["alex","日天","老男孩"]
names.clear()
print(names) # []
names = ["alex","日天","老男孩"]
names.reverse()
print(names) # ['老男孩', '日天', 'alex']
sort() 函数用于对原列表进行排序,如果指定参数,则使用比较函数指定的比较函数。
list.sort( key=None, reverse=False)
data = [
{
"id": 1,
"name": "xixi",
"percent": "59%"
},
{
"id": 2,
"name": "alex",
"percent": "100%"
},
{
"id": 3,
"name": "andy",
"percent": "20%"
},
{
"id": 4,
"name": "red",
"percent": "60%"
},
{
"id": 5,
"name": "cat",
"percent": "80%"
},
]
print(data)
定义排序函数
def takeSortID(elem):
return int(elem['id'])
def takeSortPercent(elem):
return int(elem['percent'].split('%')[0])
data.sort(key=takeSortPercent, reverse=True) # 不用再次赋值变量
print(data)
data.sort(key=takeSortID, reverse=True) # 不用再次赋值变量
print(data)
l2 = ['a','a']
num = l2.index('a')
print(num)
# 0
res_info['data']['items'] = dbList[(page-1)*limit:page*limit]
v1 = bool([11,22,33]) # True
v2 = bool([]) # False
v3 = str([11,22,33]) # "[11,22,33]"
v4 = list("alex") # ['a', 'l', 'e', 'x']
划重点:空列表转换布尔值为False;其他类型转列表 list(其他数据),内部是循环数据并将数据的每个元素添加到列表中。
v1 = [11,22,33]
# v1[1] = 88
v2 = ["alex",18,True]
v3 = ["alex",18,[11,22,33], True]
v4 = ["alex",18,[11,22,["alex","eric"]], True]
# 练习题
data = ["alex",18,[11,22,["tony","eric"]], True]
# 1. 获取18
data[1]
# 2. 找到alex中的x
data[0][-1]
# 3. 将22修改成88
data[2][1] = 88
print(data)
# 4.在eric后面追加一个"日天"
data[2][2].append("日天")
print(data)
# 5.在22前面插入 "老男孩"
data[2].insert(1,"老男孩")
print(data)
# 6. 将列表中的eric变为大写(列表中需要改变)
data[2][2][1] = data[2][2][1].upper()
data_list = [11,22,33,44,55,66,77,88]
# 请实现删除列表的第1,3,4索引的值,即:22,44,55。
del data_list[4]
del data_list[3]
del data_list[1]
注意:如果以后遇到删除列表的数据,索引变化问题(从后向前删)。
特殊的列表
元组是一个 有序 的 容器,当我们在程序中想要表示多个数据,都可以使用元组(元素的元素不可被修改)。
v1 = (11,22,33)
v2 = (True,"alex",False,123)
v3 = (True,"alex",False,123,[11,22,33,44])
# 强制要求,定于元组时候在最后一个元素的位置多写一个逗号。
v1 = (11,22,33, )
v2 = (True,"alex",False,123, )
v3 = (True,"alex",False,123,[11,22,33,44], )
v1 = (1) # 整型 1
v2 = 1 # 整型 1
v3 = (1,) # 元组 (1,)
# 面试题:a = [1,2,3] 和 b = [(1),(2),(3) ] 以及 c = [(1,),(2,),(3,) ] 的区别?
v1 = (11,22,33)
print( len(v1) )
v1 = (11,22,33)
v1[0]
v1[1]
v1[2]
v1[0] = 999 # 错误
del v1[0] # 错误
v1 = (11,22,33)
v1[0:2]
v1 = (11,22,33)
v1[::2]
v1 = (11,22,33)
for item in v1:
print(item)
v1 = (11,22,33)
for i in range(len(v1)):
print(i, v1[i] )
v1 = bool( (11,22,333,) ) # True
v2 = bool( () ) # False
v3 = str((11,22,33)) # "(11,22,33)"
v4 = list( (11, 22, 33,) ) # [11,22,33]
name = "武沛齐"
data = tuple(name) # ('武', '沛', '齐')
names = ["alex","eric","tony"]
result = tuple(names) # ("alex","eric","tony")
划重点:空元组转换布尔值是False,其他都是True;其他类型转元组。
元组的元素不允许被重置(个数和内容都不允许)
v1 = (11,22,33)
v2 = (1,True,False,"alex",3.14)
v3 = (11,22,["alex","tony"],True)
v3[0] = 123 # 错误
v3[2] = [11,22,33] # 错误
v3[2][1] = "武沛齐" # 正确
# 练习题
data = (
11,
[
6,
7,
(3.14,9.99,88,),
8
],
22,
(
"alex",
(111),
"eric",
["中国","美国","俄罗斯"]
),
99
)
# data[0] = 123
# data[1] = [2,3]
# data[1].insert(2,7.5)
# 1. 将22换成33,是否支持?,不支持。
# 2. 在7的后面添加一个7.5.
data[1].insert(2,7.5)
# 3. 获取 111这个值。
data[3][1]
# 4. 在alex前面添加“日天”,不支持。
user_list = ["alex|123","eric|666","tony|admin"]
user = input("请输入用户名:")
pwd = input("请输入密码:")
flag = False
for item in user_list:
item_list = item.split('|') # ["用户名","密码"]
if item_list[0] == user and item_list[1] == pwd:
print("登录成功")
flag = True
break
if flag:
print("登录成功")
else:
print("登录失败")
user_list = [ ("alex","123"),("eric","666"),]
...
user_list = []
print("请录入用户信息")
while True:
name = input("请输入用户名(Q/q):")
if name.upper() == "Q":
break
pwd = input("请输入密码:")
package = (name,pwd,)
user_list.append(packge)
print("用户认证")
...