Heim  >  Fragen und Antworten  >  Hauptteil

python - 包含字节的字符串,如何解码

代码如下:

str1 = '\xB4\xF3\xE5N'

请问在python3中,如何把变量str1转成utf-8的字符串.

原编码gbk。字符串中的内容,是从网页采集的内容中的一段。

PHP中文网PHP中文网2741 Tage vor374

Antworte allen(4)Ich werde antworten

  • 大家讲道理

    大家讲道理2017-04-18 10:01:41

    >>> str1 = '\xB4\xF3\xE5N'
    >>> str1
    '´óåN'
    >>> bytes(str1,'l1').decode('gbk')
    '大錘'
    >>> unicode = _
    >>> unicode
    '大錘'
    >>> utf8=unicode.encode('utf8')
    >>> utf8
    b'\xe5\xa4\xa7\xe9\x8c\x98'
    >>> 

    Antwort
    0
  • PHPz

    PHPz2017-04-18 10:01:41

    >>> import unicodedata
    >>> unicodedata.decomposition(u'\xb4')
    '<compat> 0020 0301'

    from: http://stackoverflow.com/ques...

    Antwort
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-18 10:01:41

    x是已经编码过了的吧,你要转utf8首先要知道他的原来编码方式。
    2.7下的方法:

    str1.decode(原编码).encode('utf8')

    至于3下,由于没用过,只能百度了下。结果是说str本来就是个unicode 那直接encode就行了吧

    bytes_str1 =str1.encode('utf8')
    print(str(bytes_str1,'utf8'))

    Antwort
    0
  • 高洛峰

    高洛峰2017-04-18 10:01:41

    答案是:

    bytes(str1,'l1')

    谢谢 “同意并接受” 童鞋

    Antwort
    0
  • StornierenAntwort