练习题:字符串加密与解密

第一部分:考点和作答区

考点:

  • 字符串操作
  • 循环
  • 条件判断
  • 函数定义

题目描述: 编写一个Python函数 encrypt_string,该函数接受一个字符串作为输入,并返回一个加密后的字符串。加密规则如下:

  1. 将字符串中的每个字符替换为其ASCII值加1。
  2. 如果字符的ASCII值加上1后超过了’z’的ASCII值,则从’a’的ASCII值开始循环。
  3. 如果字符的ASCII值加上1后超过了’Z’的ASCII值,则从’A’的ASCII值开始循环。
  4. 如果字符的ASCII值加上1后超过了’9’的ASCII值,则从’0’的ASCII值开始循环。

例如,输入字符串 "Hello World!" 应返回 "Ifmmp Xpsme!"

# 请在此处编写你的代码

第二部分:答案

def encrypt_string(s):
    encrypted_chars = []
    for char in s:
        # 获取字符的ASCII值
        ascii_value = ord(char)
        # 检查是否为大写字母
        if 'A' <= char <= 'Z':
            # 循环到大写字母的ASCII值
            if ascii_value + 1 > ord('Z'):
                ascii_value = ord('A')
        # 检查是否为小写字母
        elif 'a' <= char <= 'z':
            # 循环到小写字母的ASCII值
            if ascii_value + 1 > ord('z'):
                ascii_value = ord('a')
        # 检查是否为数字
        elif '0' <= char <= '9':
            # 循环到数字的ASCII值
            if ascii_value + 1 > ord('9'):
                ascii_value = ord('0')
        # 加密字符的ASCII值
        encrypted_ascii = ascii_value + 1
        # 添加加密后的字符到列表
        encrypted_chars.append(chr(encrypted_ascii))
    # 返回加密后的字符串
    return ''.join(encrypted_chars)

# 测试代码
test_string = "Hello World!"
print(encrypt_string(test_string))  # 输出应为 "Ifmmp Xpsme!"

扩展考点:

  • 字符串切片
  • 字符串方法(如:split, join, replace
  • 正则表达式(re模块)

扩展题目描述: 扩展 encrypt_string 函数,使其能够支持多轮加密。每轮加密都会按照之前的规则进行操作。

作答区

# 请在此处编写你的代码

答案:

def encrypt_string(s, n):
    for _ in range(n):
        encrypted_chars = []
        for char in s:
            # 获取字符的ASCII值
            ascii_value = ord(char)
            # 检查是否为大写字母
            if 'A' <= char <= 'Z':
                # 循环到大写字母的ASCII值
                if ascii_value + 1 > ord('Z'):
                    ascii_value = ord('A')
            # 检查是否为小写字母
            elif 'a' <= char <= 'z':
                # 循环到小写字母的ASCII值
                if ascii_value + 1 > ord('z'):
                    ascii_value = ord('a')
            # 检查是否为数字
            elif '0' <= char <= '9':
                # 循环到数字的ASCII值
                if ascii_value + 1 > ord('9'):
                    ascii_value = ord('0')
            # 加密字符的ASCII值
                encrypted_ascii = ascii_value + 1
            # 添加加密后的字符到列表
                encrypted_chars.append(chr(encrypted_ascii))
                s = ''.join(encrypted_chars)
    return s
    www.yzhjrcw.com
    www.xgalrcw.com
    www.hyqdrc.com
    www.yylxrcw.com
    www.ccysrcw.com
# 测试代码
test_string = "Hello World!"
n = 2  # 加密两轮
print(encrypt_string(test_string, n))  # 输出应为 "Ifmmp Xpsme!Ifmmp Xpsme!"
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值