Translate password (simple uppercase and lowercase English letters are shifted by four digits, other characters remain unchanged) C language and Python version

Topic and analysis

  • Upload picture~~~
    Insert picture description here

C language implementation (using ASCLL code)

// 译密码: 使用ASCLL码,转换
#include <stdio.h>

int main()
{
    
    
	// 1. 首先接收字符,我把它定义为 str,因为输出类似一个字符串
	char str;
	printf("请输入要进行转换的一段话(英文字母加字符:)\n");
	str = getchar();
	while (str != '\n')
	{
    
    
		// 2. 判断是否为 a-z,A-Z ,不是就不动
		if ((str >= 'a' && str <= 'z') || (str >= 'A' && str <= 'Z'))
		{
    
    
			// 3. 如果 > w  >W  表示要转换为 a等, 转换方式不一样。
			if ((str >= 'w' && str <= 'z') || (str >= 'W' && str <= 'Z'))
				str = str + 4 - 26;  
			else 
			// 常规 +4 转换
				str = str + 4;
		}
		printf("%c", str);

		// c语言这种直接输入一行字符串的方法,可以记住。
		str = getchar(str);
	}
	printf("\n");
	return 0;	
}

Python implementation (using function~)

  • Also use ASCLL code
  • Python gives here, the function of encryption and decryption .
def encrypt(str_c):
    result = ''
    for i in str_c:
        if i.islower():
            result += chr((ord(i) - ord('a') + 4)%26 + ord('a'))
        elif i.isupper():
            result += chr((ord(i) - ord('A') + 4)%26 + ord('A'))
        else:
            result += i
    return result

def decrypt(str_a):
    result = ''
    for i in str_a:
        if i.islower():
        	# 这里和C语言不一样, python -3%26 = 23, C语言 -3%26 = -3
            result += chr((ord(i) - ord('a') - 4)%26 + ord('a'))
        elif i.isupper():
            result += chr((ord(i) - ord('A') - 4)%26 + ord('A'))
        else:
            result += i
    return result

# print(encrypt('i" laohu you wxyzaa..'))
print(decrypt(' ABCD'))

Guess you like

Origin blog.csdn.net/pythonstrat/article/details/112713470