Python将字节字符串转换为字节数组 [英] Python convert strings of bytes to byte array

查看:753
本文介绍了Python将字节字符串转换为字节数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,给定任意字符串。可能是个字符或只是随机的个字节

For example given an arbitrary string. Could be chars or just random bytes:

string = '\xf0\x9f\xa4\xb1'

我要输出:

b'\xf0\x9f\xa4\xb1'

这似乎很简单,但是我找不到任何答案。当然,只需在字符串后输入 b 即可。但是我想执行此运行时,或者从包含字节字符串的变量中执行。

This seems so simple, but I could not find an answer anywhere. Of course just typing the b followed by the string will do. But I want to do this runtime, or from a variable containing the strings of byte.

如果给定的 string AAAA 或某些已知的字符我可以简单地执行 string.encode('utf-8 '),但我希望字节字符串只是随机的。对'\xf0\x9f\xa4\xb1'(随机字节)这样做会产生意外结果 b'\xc3\ xb0\xc2\x9f\xc2\xa4\xc2\xb1'

if the given string was AAAA or some known characters I can simply do string.encode('utf-8'), but I am expecting the string of bytes to just be random. Doing that to '\xf0\x9f\xa4\xb1' ( random bytes ) produces unexpected result b'\xc3\xb0\xc2\x9f\xc2\xa4\xc2\xb1'.

必须有一种更简单的方法

There must be a simpler way to do this?

编辑:

我想将字符串转换为字节而不使用编码

I want to convert the string to bytes without using an encoding

推荐答案

我找到了可行的解决方案

I found a working solution

import struct

def convert_string_to_bytes(string):
    bytes = b''
    for i in string:
        bytes += struct.pack("B", ord(i))
    return bytes       

string ='\ \xf0\x9f\xa4\xb1'

print(convert_string_to_bytes(string))

输出:
b'\xf0\x9f\xa4\xb1'

这篇关于Python将字节字符串转换为字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆