【问题标题】:How to get the bytes format from a string variable without any encoding grammar in python3python3中如何在没有任何编码语法的情况下从字符串变量中获取字节格式
【发布时间】:2018-03-02 07:11:49
【问题描述】:

s1='a\xff'

我想从 s1 中获取 b'a\xff',但 s1 是一个变量,不是纯已知字符串,我如何在 python3 中获取 b'a\xff' 作为结果? 我试过这个:

b'%s' % s1

但是得到类型错误,然后我尝试在这段代码s1.encode()中使用encode,但结果是b'a\xc3\xbf'(因为python3使用默认编码'utf8'),而不是b'a\xff'

【问题讨论】:

    标签: string python-3.x byte


    【解决方案1】:
    In [149]: s1='a\xff'
    
    In [151]: s3=b"".join([b'%c' % ord(each) for each in s1])
    
    In [152]: s3==b'a\xff'
    Out[152]: True
    

    %s用于string类型变量,string类型的范围是-128~128,但是\xff是256(超出string范围),refer

    【讨论】:

    • 虽然此代码可能会回答问题,但提供有关此代码为何和/或如何回答问题的额外上下文可提高其长期价值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-09
    • 1970-01-01
    • 2019-06-11
    • 2021-01-16
    相关资源
    最近更新 更多