【问题标题】:Can't convert \x value to bytes format无法将 \x 值转换为字节格式
【发布时间】:2022-07-01 22:05:30
【问题描述】:

我正在尝试将\x 字符串值转换为字节格式对象,但是当我尝试运行以下代码时:

print(b"\x")

它会抛出一个 SyntaxError 异常:

SyntaxError: (value error) invalid \x escape at position 0

我也试过了:

print(bytes("\x"))

但这一次,异常变为:

SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 0-1: truncated \xXX escape

\x 字符似乎有问题,因为\n 在第一种方法上完美运行。我希望能够创建字节对象b'\x' 而不会出现上述错误。

提前致谢。

【问题讨论】:

    标签: python python-3.x string encoding


    【解决方案1】:

    您可以通过以下方式将任何字符串转换为字节:

    string_to_convert = "/x"
    >>> print(bytes(string_to_convert, 'utf-8'))
    b'/x'
    
    

    希望对你有帮助:)

    【讨论】:

    • 输出应该是b'\x',而不是b'/x'
    猜你喜欢
    • 2015-01-12
    • 2021-08-09
    • 2016-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多