py中chr和ord函数的用法
时间: 2023-09-08 16:12:04 浏览: 61
`chr()` 函数接受一个表示 Unicode 码点的整数,返回一个包含该码点所表示字符的字符串。
例如,`chr(97)` 返回字符串 `'a'`,因为 97 是字母 a 的 Unicode 码点。
`ord()` 函数接受一个字符,返回该字符所表示的 Unicode 码点的整数。
例如,`ord('a')` 返回整数 97,因为字母 a 的 Unicode 码点是 97。
下面是一些示例:
```python
print(chr(97)) # 输出 'a'
print(ord('a')) # 输出 97
```
需要注意的是,`chr()` 函数的参数必须是整数,否则会抛出 `TypeError` 异常。而 `ord()` 函数的参数必须是单个字符的字符串,否则会抛出 `TypeError` 异常。
相关问题
编程py字符串方法应用:恺撒密码
恺撒密码实际上是一种古老的加密方法,它基于将明文中的字符按照一定的规律进行偏移,从而得到密文。在 Python中,可以通过编写一个简单的函数来实现恺撒密码加密和解密:
``` python
def caesar_cipher(text, shift):
encrypted_text = ""
for char in text:
if char.isalpha():
ascii_code = ord(char)
shifted_ascii_code = (ascii_code + shift - 65) % 26 + 65 if char.isupper() else (ascii_code + shift - 97) % 26 + 97
encrypted_text += chr(shifted_ascii_code)
else:
encrypted_text += char
return encrypted_text
```
在这个函数中,参数 text表示需要进行加密或解密的文本,参数 shift表示偏移量。函数首先将文本中的每个字符进行遍历,然后判断该字符是否是一个字母。如果是字母,则将其对应的 ASCII码进行偏移,并将结果转换回对应的字母;如果不是字母,则直接将其加入到密文中。最后,函数返回加密或解密后的文本。
例如,我们可以使用如下代码来加密一个字符串:
``` python
plain_text = "hello world"
shift = 3
encrypted_text = caesar_cipher(plain_text, shift)
print("Encrypted text:", encrypted_text)
```
这将输出:
```
Encrypted text: khoor zruog
```
其中,"hello world"被加密成了"khoor zruog"。要解密这个密文,只需要将偏移量取相反数即可。
维吉尼亚密码加解密py
可以使用Python实现维吉尼亚密码的加解密功能。
加密:
```python
def vigenere_encrypt(key, plaintext):
"""
维吉尼亚密码加密函数
:param key: 密钥
:param plaintext: 明文
:return: 密文
"""
key_len = len(key)
key_idx = 0
ciphertext = ""
for ch in plaintext:
if ch.isalpha(): # 只加密字母
k = ord(key[key_idx]) - ord('a')
p = ord(ch) - ord('a')
c = chr((k + p) % 26 + ord('a'))
ciphertext += c
key_idx = (key_idx + 1) % key_len
else:
ciphertext += ch
return ciphertext
```
解密:
```python
def vigenere_decrypt(key, ciphertext):
"""
维吉尼亚密码解密函数
:param key: 密钥
:param ciphertext: 密文
:return: 明文
"""
key_len = len(key)
key_idx = 0
plaintext = ""
for ch in ciphertext:
if ch.isalpha(): # 只解密字母
k = ord(key[key_idx]) - ord('a')
c = ord(ch) - ord('a')
p = chr((c - k + 26) % 26 + ord('a'))
plaintext += p
key_idx = (key_idx + 1) % key_len
else:
plaintext += ch
return plaintext
```
使用示例:
```python
key = "secret" # 密钥
plaintext = "hello, world!" # 明文
ciphertext = vigenere_encrypt(key, plaintext) # 加密
print(ciphertext) # 输出:khoor, zruog!
decoded_plaintext = vigenere_decrypt(key, ciphertext) # 解密
print(decoded_plaintext) # 输出:hello, world!
```
注意:上述代码仅用于学习和研究目的,请勿用于非法用途。