python练习题

常用获取A-Z的python方法

1. if ("A"<=item<="Z")

2.ord 将字符转换成ASCII码,chr(将ASCII码转换成字符)


# 大小写相差32 a与A ascll码差值
str = input("请输入一个字符串:")
def fun(str):
    lst = []
    for item in str:
        if 'A'<=item<="Z":
             lst.append(chr(ord(item) + 32))#字符串转小写
        elif "a"<=item<="z":#A-Z 65-90 这个范围是大写字母
            lst.append(chr(ord(item) - 32))#字符串转大写
        else:
            lst.append(item)
    return "".join(lst)
#ord(将字符转换成ASCII码) chr(将ASCII码转换成字符)
#print( c + " 的ASCII 码为", ord(c))
# print( a , " 对应的字符为", chr(a))
print(fun(str))

解包

return返回两个是一个元组,然后利用解包得到两个

str = input("请输入一个字符串:")
def get_num(str):
    lst = []
    for item in str:
        if item.isdigit():
            lst.append(eval(item))
    s = sum(lst)
    return lst,s#元组类的
print(get_num(str))
lst,s = get_num(str)#解包
print(lst)
print(s)
 就是这是啥子哦 简单生成随机数

lst =[random.randint(1,100) for i in range(10)]#随机生成10个1-100的整数

#随机获得一组数 返回最大的
import random
def get_max(lst):
    max = lst[0]
    for i in lst:
        if i > max :
            max = i
    return max
lst =[random.randint(1,100) for i in range(10)]#随机生成10个1-100的整数
print(lst)
print(get_max(lst))
两种判断有无重复数的方式 

第一种 看这个元素在列表中出现的次数有没有超过两次

第二种 用集合去重,看前后序列长度是否变化

a = list(input())
isFlag = False
for i in a:
    if a.count(i) >= 2:
        isFlag = True
        break
if isFlag:
    print("True")
else:
    print("False")
# 去重的另一个思路 用集合去重 然后比较前后序列长度是否变化
 eval去引号
# eval() 去引号
# str = eval(input())
# print(str,type(str)) 

密文 也有ASCII码

# word = input("请输入原文:")
# new_word = ""
# for item in word:
#     if item == " ":
#         new_word += item
#     else:
#         num = ord(item)#ord() 将字符转换成ASCII码
#         if num in range(ord("a"),ord("x")):
#             new_word += chr(num+3)#chr() 将ASCII码转换成对应字符
#         else:
#             new_word += chr(num + 3 - 26)
# print("密文为:" + new_word)

 

python中交换两个元素的位置 

lst[index],lst[index+1] = lst[index+1],lst[index]

lst = [0,12,0,3,0,12,0]
for i in range(lst.count(0)):#获取0出现的个数
    for index in range(len(lst)-1-i):#for循环
        if lst[index] == 0:#如果是0就和后一位元素交换位置
            lst[index],lst[index+1] = lst[index+1],lst[index]
print(lst)

 

这道题的两种思路:

①for循环 遇到0交换位置

②把非零数取出来放入新的列表 统计0出现的次数 利用循环把0放入新集合

lst = [0,12,0,3,12]
new_lst = []
for item in lst:#取出不是0的数放进新数组
    if item != 0:
        new_lst.append(item)
num = lst.count(0)#统计0出现的次数
for _ in range(num):#利用循环把0放入新数组
    new_lst.append(0)
print(new_lst)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值