代码之家  ›  专栏  ›  技术社区  ›  srdg

如何在Python 3中解析ByTestString?

  •  4
  • srdg  · 技术社区  · 8 年前

    基本上,我在一行中有两个bytestring,如下所示:

    b'\xe0\xa6\xb8\xe0\xa6\x96 - \xe0\xa6\xb6\xe0\xa6\x96\n'
    

    这是一个 Unicode 正在使用从联机文件导入的字符串 urllib ,我想比较各个ByTestRing,以便替换错误的。然而,我无法找到任何方法来解析字符串,以便 \xe0\xa6\xb8\xe0\xa6\x96 \xe0\xa6\xb6\xe0\xa6\x96 在两个不同的变量中。

    我试着把它转换成一个原始字符串 str(b'\xe0\xa6\xb8\xe0\xa6\x96') 索引实际上是可行的,但在这种情况下,我首先无法恢复到原始的bytestring。

    有可能吗?

    2 回复  |  直到 4 年前
        1
  •  3
  •   Peter Mortensen Pieter Jan Bonestroo    4 年前

    我建议你试试这样的。。。

    arr = b'\xe0\xa6\xb8\xe0\xa6\x96 - \xe0\xa6\xb6\xe0\xa6\x96\n'
    
    splt = arr.decode().split(' - ')
    
    b_arr1 = splt[0].encode()
    b_arr2 = splt[1].encode()
    

    我在Python 3终端上试用过,效果很好。

        2
  •  0
  •   Jahongir Rahmonov    8 年前

    我会这样做:

    a = b'\xe0\xa6\xb8\xe0\xa6\x96 - \xe0\xa6\xb6\xe0\xa6\x96\n'
    
    parts = [part.strip() for part in a.decode().split('-')]
    
    first_part = parts[0].encode()
    second_part = parts[1].encode()