20180820学习日报-第五章 字符串练习题

字符串的练习题
1、将一个正整数分解质因数
import math
def prime_numbers(num_range):
prime_nums = []
for i in range(2,num_range+1):
for j in range(2, int(math.sqrt(i))+1):
if i%j == 0:
break
else:
prime_nums.append(i)
return prime_nums

input_number = int(input(“请输入正整数:”))
primelist = prime_numbers(input_number)
result =”“

for k in primelist:
while 1:
if input_number % k == 0:
result += str(k)+”*”
input_number = input_number / k
else:
break

print(result.strip(“*”))

执行结果:
请输入正整数:100
2*2*5*5

请输入正整数:10
2*5

请输入正整数:50
2*5*5

请输入正整数:90
2*3*3*5

请输入正整数:97
97

2、一个字符串中,分别输出奇数坐标字符或偶数坐标字符,奇数坐标的一行,偶数坐标的一行
str1 = input(“请输入一串字符:”)
even_str1 = “”
odd_str1 = “”

for i in range(len(str1)):
if i%2 == 0:
even_str1 += str1[i]
else:
odd_str1 += str1[i]
print(“even_str1:”,even_str1)
print(“odd_str1:”,odd_str1)

执行结果:

请输入一串字符:bahhdhll
even_str1: bhdl
odd_str1: ahhl

3、统计字符串中的字母、数字、其他字符个数
str1 = input(“请输入一串字符:”)
letter_num = 0
digit_num = 0
other_num = 0
for i in str1:
if i.isalpha():
letter_num += 1
elif i.isdigit():
digit_num += 1
else:
other_num += 1

print(“字符串中的字母个数:”+str(letter_num))
print(“字符串中的数字个数:”+str(digit_num))
print(“字符串中的其他字符个数:”+str(other_num))

执行结果:
请输入一串字符:18rrlll**%
字符串中的字母个数:5
字符串中的数字个数:2
字符串中的其他字符个数:3
第五章 字符串
4、有一个已经排好序的列表。现输入一个数,要求按原来的规律将它插入列表中
list1=[1,4,7,10,12]
insert_num = int(input(“请输入一个数字:”))

if insert_num <= list1[0]:
list1.insert(0,insert_num)
elif insert_num >= list1[-1]:
list1.insert(len(list1)+1,insert_num)
else:
for i in range(len(list1)-1):
if insert_num > list1[i] and insert_num <= list1[i+1]:
list1.insert(i+1,insert_num)
break

print(list1)

执行结果:
请输入一个数字:-1
[-1, 1, 4, 7, 10, 12]
请输入一个数字:2
[1, 2, 4, 7, 10, 12]
请输入一个数字:4
[1, 4, 4, 7, 10, 12]
请输入一个数字:11
[1, 4, 7, 10, 11, 12]
请输入一个数字:13
[1, 4, 7, 10, 12, 13]
请输入一个数字:12
[1, 4, 7, 10, 12, 12]
请输入一个数字:10
[1, 4, 7, 10, 10, 12]
请输入一个数字:15
[1, 4, 7, 10, 12, 15]

5、统计名字列表中,各名字的首字母在名字列表中出现的次数

list_name=[‘vivian’,’kate’,’david’,’lucy’,’willan’,’eason’]
for i in range(len(list_name)):
first_letter=list_name[i][0]
first_letter_count=str(list_name).count(list_name[i][0])
print(“第%d个名字的首字母为%s,字母%s在名字列表中出现的次数%d”%(i,first_letter,first_letter,first_letter_count))

执行结果:
第0个名字的首字母为v,字母v在名字列表中出现的次数3
第1个名字的首字母为k,字母k在名字列表中出现的次数1
第2个名字的首字母为d,字母d在名字列表中出现的次数2
第3个名字的首字母为l,字母l在名字列表中出现的次数3
第4个名字的首字母为w,字母w在名字列表中出现的次数1
第5个名字的首字母为e,字母e在名字列表中出现的次数2

6、字符替换
1)读入一个字符串
2)去掉字符串的前后空格
3)如果字符串包含数字则1替换成a,2替换成b,3替换成c,以此类推
4)将字符串使用空格进行切分,存到一个列表,然后使用*号连接,并输出
5)把这些功能封装到一个函数里面,把执行结果作为返回值

def replace_str(input_str):
if isinstance(input_str, str):
temp = input_str.strip()
temp2 = “”
for i in range(len(temp)):
if temp[i].isdigit():
temp2 +=chr(ord(temp[i]) + 48)
else:
temp2 +=temp[i]
temp3 = list(temp2)
result = “*”.join(temp3)
return result
else:
return False

print(replace_str(” 123efg “))
print(replace_str(” 578ABX “))
print(replace_str([1,2,3,]))

执行结果:
a*b*c*e*f*g
e*g*h*A*B*X
False

7、找出字符串中出现次数最多的字符,并输出其出现的位置
input_str =”abdljlgijkgoirkmrikrikk”
max = 0
letter =””
position =[]
for i in input_str:
if input_str.count(i)>max:
max = input_str.count(i)
letter = i
for j in range(len(input_str)):
if input_str[j]== letter:
position.append(str(j))

print(“字符串中出现次数最多的字符为:”+letter+”,次数为:”+str(max)+”,其出现的位置为:”+”,”.join(position))

执行结果:
字符串中出现次数最多的字符为:k,次数为:5,其出现的位置为:9,14,18,21,22

8、找出一段句子中最长的单词及其索引位置,以字典返回
dict = {}
sentence=”I am a boy,My favorite fruit is apples!”
for i in sentence:
if not i.isalpha():
sentence_new=sentence.replace(i,” “)
sentence=sentence_new
sentence_new = sentence_new.split()
for j in sentence_new:
k = j
v = len(j)
dict[k]=v

print(dict)
print(“最长单词为:”,max(dict,key=dict.get))
max_word = max(dict,key=dict.get)
for k in range(len(sentence)-len(max_word)):
if sentence[k:k+len(max_word)] == max_word:
print(“其索引位置为:”,k)
break

执行结果:

{‘I’: 1, ‘am’: 2, ‘a’: 1, ‘boy’: 3, ‘My’: 2, ‘favorite’: 8, ‘fruit’: 5, ‘is’: 2, ‘apples’: 6}
最长单词为: favorite
其索引位置为: 14

第五章 字符串的练习题
9、字母游戏
“Pig Latin”是一个英语儿童文字改写游戏,整个游戏遵从下述规则:
(1). 元音字母是‘a’、‘e’、‘i’、‘o’、‘u’。字母‘y’在不是第一个字母的情况下,也被视作元音
字母。其他字母均为辅音字母。例如,单词“yearly”有三个元音字母(分别为‘e’、‘a’和最后一个
‘y’)和三个辅音字母(第一个‘y’、‘r’和‘l’)。
(2). 如果英文单词以元音字母开始,则在单词末尾加入“hay”后得到“Pig Latin”对应单词。例如,“ask”
变为“askhay”,“use”变为“usehay”。(同上)
(3). 如果英文单词以‘q’字母开始,并且后面有个字母‘u’,将“qu”移动到单词末尾加入“ay”后得到
“Pig Latin”对应单词。例如,“quiet”变为“ietquay”,“quay”变为“ayquay”。
(4). 如果英文单词以辅音字母开始,所有连续的辅音字母一起移动到单词末尾加入“ay”后得到“Pig Latin”
对应单词。例如,“tomato”变为“omatotay”, “school” 变为“oolschay”,“you” 变为
“ouyay”,“my” 变为“ymay ”,“ssssh” 变为“sssshay”。
(5). 如果英文单词中有大写字母,必须所有字母均转换为小写。
输入格式:
一系列单词,单词之间使用空格分隔。
输出格式:
按照以上规则转化每个单词,单词之间使用空格分隔。
输入样例:
Welcome to the Python world Are you ready
输出样例:
elcomeway otay ethay ythonpay orldway arehay ouyay eadyray

代码:

coding=utf-8

def isvowels(letter, word):
if letter in (‘a’, ‘e’, ‘i’, ‘o’, ‘u’):
return True
elif letter == “y”:
for i in range(len(word)):
if word[i] == letter and i != 0:
return True
return False
return False

def consonants_change(word):
result = “”
flag = False
for i in range(len(word)):
if isvowels(word[i], word) != True:
result += word[i]
else:
flag = True
break
if flag:
result = word[i:len(word)] + result + “ay”
else:
result = result + “ay”
return result

sentence = input(“请输入一系列单词,单词之间使用空格分隔:”)
sentenc_tmp = “”
for k in sentence:
if ord(k) >= 65 and ord(k) <= 90:
sentenc_tmp += chr(ord(k) + 32)
else:
sentenc_tmp += k

sentence_new = sentenc_tmp.split()
result = []
for j in sentence_new:
if isvowels(j[0], j):
result.append(j + “hay”)
elif j[0:2] == ‘qu’:
result.append(j[2:len(j)] + “qu” + “ay”)
else:
result.append(consonants_change(j))

Pig_Latin_result = ” “.join(result)
print(“Pig Latin输出为:%s” %Pig_Latin_result)

执行结果:
请输入一系列单词,单词之间使用空格分隔:Welcome to the Python world Are you ready
Pig Latin输出为:elcomeway otay ethay ythonpay orldway arehay ouyay eadyray

字符串的练习题
10、实现字符串的upper、lower以及swapcase方法

tmp = ‘a’
tmp.upper()
‘A’
tmp.lower()
‘a’
tmp.swapcase()
‘A’

tmp2 = ‘A’
tmp2.upper()
‘A’
tmp2.lower()
‘a’
tmp2.swapcase()
‘a’

tmp3 = ‘1’
tmp3.upper()
‘1’
tmp3.lower()
‘1’
tmp3.swapcase()
‘1’

将字符中的大写都换成小写,小写换成大写
第一种写法:
import string
str1 = “123abcdBIIKOO”
result =””
for i in str1:
if i in string.ascii_lowercase:
result+=i.upper()
elif i in string.ascii_uppercase:
result+=i.lower()
else:
result+=i
print(result)

执行结果:
123ABCDbiikoo

第二种写法:
import string
str1 = “123abcdBIIKOO”
result =””
for i in str1:
if i in string.ascii_letters:
result+=i.swapcase()
else:
result+=i
print(result)

执行结果:
123ABCDbiikoo

11、实现字符串的find方法
找到字符串中所有的”a”
str1 = “123abcdBIIKOOaba”
print(str1.find(“a”)) #返回substr的第一个字母的标号
print(str1.find(“a”,5))
print(str1.find(“a”,1,5))

执行结果:
3
13
3

12、实现字符串的isalpha方法
13、实现字符串的isdigit方法

统计字符串中的字母的个数,数字的个数,
str1 = “123abcdBIIKOOaba”
letter_count = 0
digit_count = 0

for i in str1:
if i.isalpha():
letter_count +=1
elif i.isdigit():
digit_count +=1

print(letter_count)
print(digit_count)

执行结果:
13
3

14、实现字符串的isalnum方法
统计列表中只有数字或字母或数字与字母组成的个数

list1 = [“abc”,”1234”,”abc12”,”12%”,”^&&12”,”ab&&”,”bc**”]
result = 0
for i in list1:
if i.isalnum():
result += 1
print(i)
print(“result:”,result)

执行结果:
abc
1234
abc12
result: 3

15、实现字符串的join方法
将列表中的元素组成字符串,以”-“分开
list1 = [“abc”,”1234”,”abc12”,”12%”,”^&&12”,”ab&&”,”bc**”]
result = “-“.join(list1)
print(result)

执行结果:
abc-1234-abc12-12%-^&&12-ab&&-bc**

16、实现字符串的replace方法
17、实现字符串的split方法
输入一个句子,将句子中的每个单词保存到一个列表中

import string
result = []
sentence = input(“请输入一条句子:”)
for i in sentence:
if i not in string.ascii_letters:
sentence_new = sentence.replace(i,” “)
sentence = sentence_new

result = sentence_new.split()

print(result)

执行结果:
请输入一条句子:this is a boy,he is smart!
[‘this’, ‘is’, ‘a’, ‘boy’, ‘he’, ‘is’, ‘smart’]

18、实现字符串的strip方法

str1 = “abc**123
result = str1.strip(“*”)
print(result)

执行结果:
abc**123

19、报数问题:有n个人围成一圈,顺序排号。从第一个人开始报数(从1到3报数),凡报到3的人退出圈子,问最后留下的是原来第几号的那位

n = int(input(‘请输入人数:’))
list_c = list(range(1, n + 1)) # 将所有人放入一个数组
count = 0
while len(list_c) > 1: # 当数组中至少有2个元素时进行循环
list_co = list_c[:] # 把原数组拷贝到新数组中,用于限制内层循环次数
for i in range(0, len(list_co)): # 内层循环开始,从第一个人开始报数
count = count + 1

    if count % 3 == 0:  # 如果count能被3整除,则是报到3的人
        list_c.remove(list_co[i])  # 把报到3的人移除原数组,进行下一次循环

print(‘最后留下的是原来的第 {} 号。’.format(list_c[0]))

执行结果:
请输入人数:10
最后留下的是原来的第 4 号。

20、由单个字母组成的list,从键盘读入两个整数m、n(n>m),打印出list[m,n]之间的字母能组成的所有n-m+1位不同的字符串

import random
import math

list = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’, ‘d’, ‘h’, ‘f’, ‘g’]
m = int(input(“输入整数m:”))
n = int(input(“输入整数n:”))
while 1:
if n <= m:
print(“输入的n的小于或等于m”)
n = int(input(“请重新输入整数n:”))
else:
break

list_tmp = list[m:n]
print(math.factorial(len(list_tmp)))
result = []
while 1:
random.shuffle(list_tmp) #将序列的所有元素随机排序
str1 = “”.join(list_tmp)
if str1 not in result:
result.append(str1)
if len(result) == math.factorial(len(list_tmp)): #math.factorial算阶乘的方法
break

print(result)

执行结果:
输入整数m:4
输入整数n:8
24
[‘ehdf’, ‘dhfe’, ‘fdeh’, ‘hdef’, ‘efhd’, ‘fhed’, ‘hefd’, ‘dehf’, ‘edfh’, ‘dhef’, ‘hfed’, ‘hdfe’, ‘fedh’, ‘hfde’, ‘fdhe’, ‘fhde’, ‘dfhe’, ‘ehfd’, ‘edhf’, ‘fehd’, ‘dfeh’, ‘hedf’, ‘efdh’, ‘defh’]

利用了一个数学知识:
4个字母,能组成的不重复单词的个数是4!=24个

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值