"""
Auther:少校
Time:2025/4/2 16:05
越努力,越幸运
"""
# 1.将字符串 "hello" 转换为全大写
print("hello".upper())
# 2.去掉字符串两端的空格
str1=" abc \t"
print(str1.strip())
# 3.将字符串按空格分割成列表
str1="a b c d"
list1=str1.split(" ")
print(list1)
# 4.用逗号连接列表['a','b','c']中的元素
list1=['a','b','c']
str1=",".join(list1)
print(str1)
# 5.统计字符串中字母'e'出现的次数
str1="abcdefgaeeedd"
print(str1.count("e"))
# 6.检查字符串是否以"py"开头
str1="python"
print(str1[0:2] == "py")
# 7.替换字符串中的所有"apple"为"orange"
str1="apple orange bunana"
str2=str1.replace("apple","orange")
print(str2)
# 8.将字符串倒序输出
str1="apple orange bunana"
print(str1[::-1])
# 9.提取字符串中第3到第5个字符(索引从0开始)
str1="apple orange bunana"
print(str1[2:5])
# 10.判断字符串是否全为数字
str1="apple orange bunana"
print(str1.isdigit())
# 11.删除字符串中的所有空格
str1="apple orange bunana"
str2=str1.replace(" ","")
print(str2)
# 12.反转字符串中的单词顺序(如"hello world" → "world hello")
str1="hello world"
str2= str1.split(" ")
print(" ".join(str2[::-1]))
# 13.统计字符串中的中文字符数量
str1 ="统计字符串中的中文字符数量"
count1=0
for x in str1:
if "\u4e00" <= x <= "\u9fa5":
count1 += 1
print(count1)
# 14.检查字符串是否为回文
str1="aba"
print(str1 == str1[::-1])
# 15.生成包含随机大小写字母的8位验证码
from random import randint, randrange
str1=""
while True:
y=randint(65,122)
if 65 <= y <= 90 or 97 <= y <= 122:
str1 += chr(y)
if len(str1) == 8:
break
print(str1)
#方法二:
list1=[chr(x) for x in range(97,97+26)] + [chr(x) for x in range(65,65+26)]
str1=""
for x in range(8):
str1 += list1[randrange(0,len(list1)-1)]
print(str1)
# ----------------------进阶--------------------------
# 1.最长无重复字符子串查找
str1="abcdefaxvbnjjbcgaeeed"
list1=[]
for x in str1:
str2 = ""
for y in str1[str1.find(x):]:
if y not in str2:
str2 += y
else:
if len(list1) < len(str2):
list1.clear()
list1.append(str2)
elif len(list1) == len(str2):
list1.append(str2)
print(list1)
# 2.自己写代码实现split方法的功能
#['hello', 'world', 'ni', 'hao']
# str1="helloyouworldyouniyouhao"
# s="you"
# result= []
# temp = ""
# index = 0
# while True:
# if str1[index:index+len(s)] != s:
# temp += str1[index]
# index += 1
# else:
# result.append(temp)
# temp=""
# index += len(s)
# if index >len(str1):
# break
# result.append(temp)
# print(result)
# 3.自己写代码实现replace方法的功能
str1="helloyouworldyouniyouhao"
old = "you"
new = "张三"
str2=""
index = 0
# for x in str1.split(old):
# str2 += x+new
# str3 = str2[0:-len(new)]
# print(str3)
while True:
if str1[index:index+len(old)] != old:
str2 += str1[index]
index += 1
else:
str2 += new
index += len(old)
if index >= len(str1):
break
print(str2)01.homework
本节1101字2025-04-07 15:59:37