可以使用encode()方法将字符串转换为字节,例如:
s = "Hello, World!" b = s.encode() print(b)
输出:
b'Hello, World!'
另外,可以使用字符编码作为参数将字符串转换为特定编码的字节,例如:
s = "你好,世界!" b = s.encode("utf-8") print(b)
输出:
b'\xe4\xbd\xa0\xe5\xa5\xbd\xef\xbc\x8c\xe4\xb8\x96\xe7\x95\x8c\xef\xbc\x81'