1.遍历字符串
for single_char in src_str:
print(single_char)

2.index函数与简单加密
index函数:检索字符串中的字符是否在给定字符串中
简单加密:
alphabet_src='abcdefghijklmnopqrstuvwxyz'alphabet_tar='defghijklmnopqrstuvwxyzabc'src_str='hello world!'for single_char in src_str:if single_char in alphabet_src:index=alphabet_src.index(single_char)print(alphabet_tar[index])
一定要注意缩进和定义的字符串名和冒号位置
invalid syntax错误:缩进和冒号错误
运行结果:alphabet_tar是密钥

以上的结果是以字符逐行输出,下面通过把字符累加到字符串上,输出加密后的一整个字符串
alphabet_src='abcdefghijklmnopqrstuvwxyz'alphabet_tar='defghijklmnopqrstuvwxyzabc'src_str='hello world!'result=''for single_char in src_str:if single_char in alphabet_src:index=alphabet_src.index(single_char)result=result+alphabet_tar[index] #转码else:result=result+single_char#空字符不转码,直接加上去print(result)

解密:
decrypted_str=''for single_char in result:if single_char in alphabet_tar:index=alphabet_tar.index(single_char)decrypted_str=decrypted_str+alphabet_src[index] #转码else:decrypted_str=decrypted_str+single_char#空字符不转码,直接加上去print(decrypted_str)#解密

3.函数的书写方法(传参别忘了标记参数)
def decryptIt(src_str): #别忘了括号里的参数decrypted_str=''for single_char in src_str:if single_char in alphabet_tar:index=alphabet_tar.index(single_char)decrypted_str=decrypted_str+alphabet_src[index] #转码else:decrypted_str=decrypted_str+single_char#空字符不转码,直接加上去return decrypted_str#解密print(decryptIt('zruog!'))
对齐问题很严重也很愁人啊~

4.如何减少歧义
global XX#使用的是全局变量
5.assert 检验代码(函数是否正确)
assert('world!'== decryptIt('zruog!'))
6.代码函数说明文档的用法
def encryptIt(src_str:str)->str:'''用于对字符串简单加密输入参数:src_str:原始文本内容返回结果:加密文本'''help(encryptIt)

7.直接计算索引位置的加密
alphabet_src='abcdefghijklmnopqrstuvwxyz'def encryptIt(src_str:str)->str:'''用于对字符串简单加密输入参数:src_str:原始文本内容返回结果:加密文本'''global alphabet_srcencrypted_str=''for single_char in src_str:if single_char in alphabet_src:old_index=alphabet_src.index(single_char)new_index=(old_index+3)%26#处理越界encrypted_str=encrypted_str+alphabet_src[new_index] #转码else:encrypted_str=encrypted_str+single_char#空字符不转码,直接加上去return encrypted_strprint(encryptIt('hello world!'))

小心字符越界的问题!这里用了取余处理越界
