基础题
1.已知字符串:“this is a test of Python”
a.统计该字符串中字母s出现的次数: count()
str1 = "this is a test of Python"
print(str1.count("s"))
b.取出子字符串“test”, 用切片,不能数: 使用find(),len()
str1 = "this is a test of Python"
start=str1.find('test')
end=start+len("test")
print(str1[start:end])
c.采用不同的方式将字符串倒序输出: 切片,循环
# 方式一:切片方式
str1 = "this is a test of Python"
print(str1[::-1])
# 方式二:
print("".join(list(reversed(str1))))
d.将其中的"test"替换为"exam" : replace
str1 = "this is a test of Python"
print(str1.replace("test","exam"))
2.去掉字符串123@zh@qq.com中的@;
提示: replace
str2 = "123@zh@qq.com"
print(str2.replace("@",""))
''' 进阶题 '''
1.已知字符串 s = "aAsmr3idd4bgs7Dlsf9eAF",要求如下
a.请将s字符串的大写改为小写,小写改为大写: swapcase()
s = "aAsmr3idd4bgs7Dlsf9eAF"
print(s.swapcase())
b.请将s字符串的数字取出,并输出成一个新的字符串: 循环,isdigit()
s = "aAsmr3idd4bgs7Dlsf9eAF"
k =''
for i in s:
if i.isdigit():
k+=i
print(k)
c.请统计s字符串出现的每个字母的出现次数(忽略大小写,a与A是同一个字母), (选做)
并输出成一个字典。 例 d = {'a':2,'s':1, 'm':1}
提示:循环,判断字符是否在字典中 'a' in d
s = "aAsmr3idd4bgs7Dlsf9eAF"
dict1 = {} # 定义一个空字典,专门接收获取出来的数据
for i in s:
if i.isdigit(): # # 检测字符串是否只由数字组成。
continue
lowerStr = i.lower() # 将字符串中的所有的字母转换为小写
if lowerStr not in dict1: # 判断小写字母是否在字典中出现
dict1[lowerStr] = 1 # 如果小写字母不在字典中,设置出现的次数为1
else:
dict1[lowerStr] += 1 # 如果小写字母在字典中已经出现,设置出现的次数加1
print(dict1)
d.输出s字符串出现频率最高的字母, 如果有多个最高,将每个都输出: max(d.values()),再循环
max_count=max(dict1.values())
print(max_count)
for k,v in dict1.items():
if v ==max_count:
print(k,end=" ")
print()
e.请判断'boy'字符串中的每一个字母,是否都出现在s字符串里。如果出现,则输出True,否则,则输出False
s = "aAsmr3idd4bgs7Dlsf9eAF"
ss2="boy"
for i in s:
if i not in s:
print(False)
break
else:
print(True)
2.将字符串按照单词进行逆序,空格作为划分单词的唯一条件
如传入:”Welome to Beijing”改为 “Beijing to Welcome”
s = 'Welome to Beijing'
提示:split, reverse, join
老师的办法
s1='Welome to Beijing'
print("".join(s1.split()[::-1]))
自己的办法
s = 'Welome to Beijing'
t =s.split()
t.reverse()
print(' '.join(t))
''' 挑战题 '''(选做)
1.输入一个字符串,压缩字符串如下aabbbccccbbd变成a2b5c4d1
s = 'aabbbccccbbd'
a2b5c4d1
count()
s2 = 'aabbbccccbbd'
dict2 = {}
for i in s2:
if i not in dict2:
dict2[i] = s2.count(i)
ss1 = "" # 定义空字符串,实现字母和数字的拼接
for k, v in dict2.items():
ss1 = ss1 + k + str(v)
print(ss1)
2,将字符中单词用空格隔开
已知传入的字符串中只有字母,每个单词的首字母大写,
请将每个单词用空格隔开,只保留第一个单词的首字母大写
传入:”HelloMyWorld”
返回:”Hello my world”
s = 'HelloMyWorld'
s3 = 'HelloMyWorld'
# 取出s3字符串中的第一个字母H
ss3 = s3[0]
for i in range(1,len(s3)):
# print(s3[i])
str3 = s3[i]
if str3.isupper(): # 如果字母是大写字母(M W) 先在Hello的后面拼接空格,然后将大写字母
#转换为小写再拼接
ss3 += ' '+str3.lower()
else:
ss3 += str3
print(ss3)
这篇博客包含了Python的基础和进阶练习题,包括字符串操作、字母转换、字符统计等。基础题涵盖字符串计数、切片、替换操作;进阶题涉及字符串大小写互换、数字提取、字母频率统计及单词逆序;挑战题则包含字符串压缩和单词首字母大写处理。
7999

被折叠的 条评论
为什么被折叠?



