Python的bytes及其方法

bytes定义
# coding:utf-8

if __name__ == '__main__':
    
    '''
    例1:通过b'string'定义bytes类型,但不支持中文(出现中文则报错)
    例2:可以通过string.encoding('utf-8')将字符串转换成bytes类型(兼容中文),还原通过bytes.decode('utf-8')
    '''

    # 例1
    b = b'abc123'
    print(b)  # b'abc123'
    print(type(b))  # <class 'bytes'>
    # c = b'我abc123' Error

    # 例2
    c = '我abc123'
    c = c.encode('utf-8')
    print(c)  # b'\xe6\x88\x91abc123'
    print(type(c))  # <class 'bytes'>
    print(c.decode('utf-8'))  # 我abc123
bytes方法
# coding:utf-8

if __name__ == '__main__':

    '''
    例1:string有的方法bytes大部分都有(但其字符串参数必须是bytes类型)
    '''
    b = b'abc123'
    print(b.find(b'a'))  # 0
    c = 'abc123'
    print(c.find('a'))  # 0
    # b.find('a') Error 参数必须是bytes
    print(b.replace(b'a', b'f'))  # b'fbc123'
    print(c.replace('a', 'f'))  # fbc123
    # b.replace('a', 'f') Error 参数必须是bytes

如果你想转换加密方法,可以使用Python中的不同加密库来实现。以下是一些常用的加密库及其示例用法: 1. hashlib库:提供许多安全哈希和消息摘要算法,例如MD5、SHA1、SHA256等。 示例代码: ```python import hashlib # 计算字符串的MD5哈希值 string = "Hello World" hash_object = hashlib.md5(string.encode()) print(hash_object.hexdigest()) # 计算文件的SHA256哈希值 filename = "test.txt" with open(filename, "rb") as f: bytes = f.read() hash_object = hashlib.sha256(bytes) print(hash_object.hexdigest()) ``` 2. cryptography库:提供了更高级的加密算法实现,例如AES、RSA等。 示例代码: ```python from cryptography.fernet import Fernet # 使用Fernet对字符串进行AES加密和解密 key = Fernet.generate_key() cipher_suite = Fernet(key) plaintext = "Hello World" cipher_text = cipher_suite.encrypt(plaintext.encode()) print(cipher_text) decrypted_text = cipher_suite.decrypt(cipher_text) print(decrypted_text.decode()) # 使用RSA生成公钥和私钥,并使用公钥加密和私钥解密 from cryptography.hazmat.primitives.asymmetric import rsa, padding from cryptography.hazmat.primitives import serialization private_key = rsa.generate_private_key( public_exponent=65537, key_size=2048 ) public_key = private_key.public_key() plaintext = b"Hello World" ciphertext = public_key.encrypt( plaintext, padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None ) ) print(ciphertext) decrypted_text = private_key.decrypt( ciphertext, padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None ) ) print(decrypted_text) ``` 以上是一些常用的加密库及其示例用法,你可以根据自己的需求选择合适的库来实现加密。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值