前言
本文已参与「新人创作礼」活动,一起开启掘金创作之路。更新一些新的python练习题供大家参考,
正文
题目(1):
-
题目:输入一个字符串str, 输出第m个只出现过n次的字符,如在字符串 gbgkkdehh 中,
找出第2个只出现1 次的字符,输出结果:d代码如下所示: def test(str_test, num, counts): """ :param str_test: 字符串 :param num: 字符串出现的次数 :param count: 字符串第几次出现的次数 :return: """
定义一个空数组,存放逻辑处理后的数据
list = []
for循环字符串的数据
for i in str_test: # 使用 count 函数,统计出所有字符串出现的次数 count = str_test.count(i, 0, len(str_test))
# 判断字符串出现的次数与设置的counts的次数相同,则将数据存放在list数组中 if count == num: list.append(i) # 返回第n次出现的字符串 return list[counts-1]print(test('gbgkkdehh', 1, 2))
结果: d 题目2:
Process finished with exit code 0
def :,为python定义函数的方式,定义好的函数方便后面编程直接1调用
-
输出指定字符串A在字符串B中最后出现的位置,如果B中不包含A, 出-1从 0 开始计数
A = “hello”
B = “hi how are you hello world, hello yoyo !”def test(string, str): # 定义 last_position 初始值为 -1 last_position = -1 while True: position = string.find(str, last_position+1) if position == -1: return last_position last_position = positionprint(test('hi how are you hello world, hello yoyo !', 'hello'))
结果: 28
Process finished with exit code 0 题目3:
-
给定一个数a,判断一个数字是否为奇数或偶数
a1 = 13
a2 = 10while True: try: # 判断输入是否为整数 num = int(input('输入一个整数:')) # 不是纯数字需要重新输入 except ValueError: print("输入的不是整数!") continue if num % 2 == 0: print('偶数') else: print('奇数') break 结果: 输入一个整数:100 偶数Process finished with exit code 0
结语
文章就到这里,下次继续更新!大家下次再见。