Hướng dẫn how do you convert a byte array into a string python? - làm thế nào để bạn chuyển đổi một mảng byte thành một chuỗi python?

Nếu bạn không biết mã hóa, thì hãy đọc đầu vào nhị phân vào chuỗi trong Python 3 và Python 2 cách tương thích, hãy sử dụng mã hóa MS-DOS CP437 cổ đại:

PY3K = sys.version_info >= (3, 0)

lines = []
for line in stream:
    if not PY3K:
        lines.append(line)
    else:
        lines.append(line.decode('cp437'))

Bởi vì mã hóa chưa được biết, mong đợi các ký hiệu không phải tiếng Anh dịch sang các ký tự của cp437 (ký tự tiếng Anh không được dịch, bởi vì chúng khớp với hầu hết các mã hóa byte đơn và UTF-8).

Giải mã đầu vào nhị phân tùy ý cho UTF-8 không an toàn, bởi vì bạn có thể nhận được điều này:

>>> b'\x00\x01\xffsd'.decode('utf-8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 2: invalid
start byte

Điều tương tự cũng áp dụng cho latin-1, rất phổ biến (mặc định?) Đối với Python 2. Xem các điểm còn thiếu trong bố cục codePage - đó là nơi Python bị nghẹn với ordinal not in range khét tiếng.

Cập nhật 20150604: Có tin đồn rằng Python 3 có chiến lược lỗi surrogateescape để mã hóa các công cụ thành dữ liệu nhị phân mà không bị mất dữ liệu và sự cố, nhưng nó cần kiểm tra chuyển đổi, [binary] -> [str] -> [binary], để xác thực cả hiệu suất và độ tin cậy.: There are rumors that Python 3 has the surrogateescape error strategy for encoding stuff into binary data without data loss and crashes, but it needs conversion tests, [binary] -> [str] -> [binary], to validate both performance and reliability.

CẬP NHẬT 20170116: Nhờ bình luận của Nearoo - cũng có khả năng cắt giảm Escape tất cả các byte chưa biết với trình xử lý lỗi backslashreplace. Điều đó chỉ hoạt động cho Python 3, vì vậy ngay cả với cách giải quyết này, bạn vẫn sẽ nhận được đầu ra không nhất quán từ các phiên bản Python khác nhau:: Thanks to comment by Nearoo - there is also a possibility to slash escape all unknown bytes with backslashreplace error handler. That works only for Python 3, so even with this workaround you will still get inconsistent output from different Python versions:

PY3K = sys.version_info >= (3, 0)

lines = []
for line in stream:
    if not PY3K:
        lines.append(line)
    else:
        lines.append(line.decode('utf-8', 'backslashreplace'))

Xem Hỗ trợ Unicode của Python để biết chi tiết.

CẬP NHẬT 20170119: Tôi quyết định thực hiện giải mã Escaping Slash hoạt động cho cả Python & NBSP; 2 và Python & NBSP; 3. Nó nên chậm hơn giải pháp cp437, nhưng nó sẽ tạo ra kết quả giống hệt nhau trên mỗi phiên bản Python.: I decided to implement slash escaping decode that works for both Python 2 and Python 3. It should be slower than the cp437 solution, but it should produce identical results on every Python version.

# --- preparation

import codecs

def slashescape(err):
    """ codecs error handler. err is UnicodeDecode instance. return
    a tuple with a replacement for the unencodable part of the input
    and a position where encoding should continue"""
    #print err, dir(err), err.start, err.end, err.object[:err.start]
    thebyte = err.object[err.start:err.end]
    repl = u'\\x'+hex(ord(thebyte))[2:]
    return (repl, err.end)

codecs.register_error('slashescape', slashescape)

# --- processing

stream = [b'\x80abc']

lines = []
for line in stream:
    lines.append(line.decode('utf-8', 'slashescape'))

Mục lục

  • Làm thế nào để tạo một bytearray từ một chuỗi?
  • Sử dụng hàm str () để chuyển đổi bytearray thành chuỗi trong python
  • Sử dụng hàm decode () để chuyển đổi bytearray thành chuỗi trong python
  • Sử dụng mô -đun codecs để chuyển đổi bytearray thành chuỗi trong python
  • Sự kết luận

Python hỗ trợ các loại đối tượng chuỗi khác nhau để lưu trữ dữ liệu. Một đối tượng như vậy là một đối tượng bytearray. Như tên cho thấy, một đối tượng bytearray là một mảng byte hoặc một chuỗi byte. Trong bài viết này, chúng tôi sẽ thảo luận về các cách khác nhau để chuyển đổi bytearray thành chuỗi trong Python.

Làm thế nào để tạo một bytearray từ một chuỗi?

Sử dụng hàm str () để chuyển đổi bytearray thành chuỗi trong python

Sử dụng hàm decode () để chuyển đổi bytearray thành chuỗi trong python

>>> b'\x00\x01\xffsd'.decode('utf-8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 2: invalid
start byte
3

Here,

  • Sử dụng mô -đun codecs để chuyển đổi bytearray thành chuỗi trong python
  • Sự kết luận
  • Python hỗ trợ các loại đối tượng chuỗi khác nhau để lưu trữ dữ liệu. Một đối tượng như vậy là một đối tượng bytearray. Như tên cho thấy, một đối tượng bytearray là một mảng byte hoặc một chuỗi byte. Trong bài viết này, chúng tôi sẽ thảo luận về các cách khác nhau để chuyển đổi bytearray thành chuỗi trong Python.
  • Trước khi chuyển đổi bytearray thành một chuỗi, trước tiên chúng ta hãy thảo luận về cách chúng ta có thể chuyển đổi một chuỗi thành một bytearray. Sau khi tạo một đối tượng bytearray từ một chuỗi, chúng ta sẽ tìm hiểu cách chuyển đổi bytearray thành một chuỗi trong các phần tiếp theo.

Để chuyển đổi một chuỗi thành một bytearray, chúng tôi sử dụng hàm tạo

>>> b'\x00\x01\xffsd'.decode('utf-8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 2: invalid
start byte
1. Cú pháp cho hàm tạo
>>> b'\x00\x01\xffsd'.decode('utf-8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 2: invalid
start byte
1 như sau.

myString="Java2Blog"="Java2Blog"

byteArrayObject=bytearray(myString,'utf-8')=bytearray(myString,'utf-8')

>>> b'\x00\x01\xffsd'.decode('utf-8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 2: invalid
start byte
4 là đầu ra được đưa ra bởi hàm tạo
>>> b'\x00\x01\xffsd'.decode('utf-8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 2: invalid
start byte
1.("The input string is:",myString)

>>> b'\x00\x01\xffsd'.decode('utf-8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 2: invalid
start byte
6 là chuỗi phải được chuyển đổi thành bytearray.("The bytearray object is:",byteArrayObject)

Output:

>>> b'\x00\x01\xffsd'.decode('utf-8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 2: invalid
start byte
7, là định dạng mã hóa mà chúng tôi tuân theo trong khi chuyển đổi một chuỗi thành bytearray. Nói chung, đó là ‘
>>> b'\x00\x01\xffsd'.decode('utf-8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 2: invalid
start byte
8, hoặc‘
>>> b'\x00\x01\xffsd'.decode('utf-8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 2: invalid
start byte
9.input stringis:Java2Blog

________ 20 & nbsp; là thông báo được hiển thị khi có bất kỳ lỗi nào xảy ra trong quá trình thực hiện hàm tạo

>>> b'\x00\x01\xffsd'.decode('utf-8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 2: invalid
start byte
1. Đó là một đối số tùy chọn.bytearray objectis:bytearray(b'Java2Blog')

Để chuyển đổi một chuỗi thành đối tượng bytearray, chúng ta có thể chuyển chuỗi đầu vào và định dạng mã hóa cho hàm tạo bytearray như sau.

Sử dụng hàm str () để chuyển đổi bytearray thành chuỗi trong python

Sử dụng hàm decode () để chuyển đổi bytearray thành chuỗi trong python

myFloat=123.4567=123.4567

myString=str(myFloat)=str(myFloat)

Sử dụng mô -đun codecs để chuyển đổi bytearray thành chuỗi trong python

myString="Java2Blog"="Java2Blog"

byteArrayObject=bytearray(myString,'utf-8')=bytearray(myString,'utf-8')

>>> b'\x00\x01\xffsd'.decode('utf-8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 2: invalid
start byte
4 là đầu ra được đưa ra bởi hàm tạo
>>> b'\x00\x01\xffsd'.decode('utf-8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 2: invalid
start byte
1.("The input string is:",myString)

>>> b'\x00\x01\xffsd'.decode('utf-8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 2: invalid
start byte
6 là chuỗi phải được chuyển đổi thành bytearray.("The bytearray object is:",byteArrayObject)

output_string=str(byteArrayObject,'utf-8')=str(byteArrayObject,'utf-8')

>>> b'\x00\x01\xffsd'.decode('utf-8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 2: invalid
start byte
7, là định dạng mã hóa mà chúng tôi tuân theo trong khi chuyển đổi một chuỗi thành bytearray. Nói chung, đó là ‘
>>> b'\x00\x01\xffsd'.decode('utf-8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 2: invalid
start byte
8, hoặc‘
>>> b'\x00\x01\xffsd'.decode('utf-8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 2: invalid
start byte
9.("The output string is:",output_string)

Output:

>>> b'\x00\x01\xffsd'.decode('utf-8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 2: invalid
start byte
7, là định dạng mã hóa mà chúng tôi tuân theo trong khi chuyển đổi một chuỗi thành bytearray. Nói chung, đó là ‘
>>> b'\x00\x01\xffsd'.decode('utf-8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 2: invalid
start byte
8, hoặc‘
>>> b'\x00\x01\xffsd'.decode('utf-8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 2: invalid
start byte
9.input stringis:Java2Blog

________ 20 & nbsp; là thông báo được hiển thị khi có bất kỳ lỗi nào xảy ra trong quá trình thực hiện hàm tạo

>>> b'\x00\x01\xffsd'.decode('utf-8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 2: invalid
start byte
1. Đó là một đối số tùy chọn.bytearray objectis:bytearray(b'Java2Blog')

Để chuyển đổi một chuỗi thành đối tượng bytearray, chúng ta có thể chuyển chuỗi đầu vào và định dạng mã hóa cho hàm tạo bytearray như sau.output stringis:Java2Blog

in ("Chuỗi đầu vào là:", MyString)

myString="Java2Blog"="Java2Blog"

byteArrayObject=bytearray(myString,'utf-8')=bytearray(myString,'utf-8')

>>> b'\x00\x01\xffsd'.decode('utf-8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 2: invalid
start byte
4 là đầu ra được đưa ra bởi hàm tạo
>>> b'\x00\x01\xffsd'.decode('utf-8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 2: invalid
start byte
1.("The input string is:",myString)

>>> b'\x00\x01\xffsd'.decode('utf-8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 2: invalid
start byte
6 là chuỗi phải được chuyển đổi thành bytearray.("The bytearray object is:",byteArrayObject)

output_string=str(byteArrayObject,'utf-16')=str(byteArrayObject,'utf-16')

>>> b'\x00\x01\xffsd'.decode('utf-8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 2: invalid
start byte
7, là định dạng mã hóa mà chúng tôi tuân theo trong khi chuyển đổi một chuỗi thành bytearray. Nói chung, đó là ‘
>>> b'\x00\x01\xffsd'.decode('utf-8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 2: invalid
start byte
8, hoặc‘
>>> b'\x00\x01\xffsd'.decode('utf-8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 2: invalid
start byte
9.("The output string is:",output_string)

Output:

>>> b'\x00\x01\xffsd'.decode('utf-8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 2: invalid
start byte
7, là định dạng mã hóa mà chúng tôi tuân theo trong khi chuyển đổi một chuỗi thành bytearray. Nói chung, đó là ‘
>>> b'\x00\x01\xffsd'.decode('utf-8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 2: invalid
start byte
8, hoặc‘
>>> b'\x00\x01\xffsd'.decode('utf-8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 2: invalid
start byte
9.input stringis:Java2Blog

________ 20 & nbsp; là thông báo được hiển thị khi có bất kỳ lỗi nào xảy ra trong quá trình thực hiện hàm tạo

>>> b'\x00\x01\xffsd'.decode('utf-8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 2: invalid
start byte
1. Đó là một đối số tùy chọn.bytearray objectis:bytearray(b'Java2Blog')

Để chuyển đổi một chuỗi thành đối tượng bytearray, chúng ta có thể chuyển chuỗi đầu vào và định dạng mã hóa cho hàm tạo bytearray như sau.(most recent call last):

  File"/home/aditya1117/PycharmProjects/pythonProject/webscraping.py",line5,inFile"/home/aditya1117/PycharmProjects/pythonProject/webscraping.py",line5,in<module>

    output_string=str(byteArrayObject,'utf-16')output_string= str(byteArrayObject,'utf-16')

UnicodedEcodeError: 'UTF-16-le'Codec không thể sử dụng byte0x67inpocation8: Dữ liệu bị cắt cụt:'utf-16-le'codec can'tdecode byte0x67inposition8:truncated data

Ở đây, bạn có thể thấy rằng phương thức

PY3K = sys.version_info >= (3, 0)

lines = []
for line in stream:
    if not PY3K:
        lines.append(line)
    else:
        lines.append(line.decode('utf-8', 'backslashreplace'))
2 không thể chuyển đổi một đối tượng bytearray thành một chuỗi vì chúng tôi đã vượt qua định dạng mã hóa giống như mẫu được sử dụng trong khi tạo đối tượng bytearray.

Sử dụng hàm decode () để chuyển đổi bytearray thành chuỗi trong python

Một cách khác để chuyển đổi bytearray thành chuỗi là bằng cách sử dụng phương thức

PY3K = sys.version_info >= (3, 0)

lines = []
for line in stream:
    if not PY3K:
        lines.append(line)
    else:
        lines.append(line.decode('utf-8', 'backslashreplace'))
7. Phương thức
PY3K = sys.version_info >= (3, 0)

lines = []
for line in stream:
    if not PY3K:
        lines.append(line)
    else:
        lines.append(line.decode('utf-8', 'backslashreplace'))
7, khi được gọi trên đối tượng bytearray, lấy định dạng mã hóa làm đầu vào và trả về chuỗi đầu ra. & NBSP;

Bạn có thể chuyển đổi bytearray thành một chuỗi bằng phương thức

PY3K = sys.version_info >= (3, 0)

lines = []
for line in stream:
    if not PY3K:
        lines.append(line)
    else:
        lines.append(line.decode('utf-8', 'backslashreplace'))
7 như sau.

myString="Java2Blog"="Java2Blog"

byteArrayObject=bytearray(myString,'utf-8')=bytearray(myString,'utf-8')

in ("Chuỗi đầu vào là:", MyString)("The input string is:",myString)

in ("đối tượng bytearray là:", bytearrayobject)("The bytearray object is:",byteArrayObject)

output_string=byteArrayObject.decode('utf-8')=byteArrayObject.decode('utf-8')

in ("Chuỗi đầu ra là:", output_string)("The output string is:",output_string)

Output:

Chuỗi đầu vào: java2bloginput stringis:Java2Blog

Đối tượng bytearray: bytearray (b'java2blog ')bytearray objectis:bytearray(b'Java2Blog')

Chuỗi đầu ra: java2blogoutput stringis:Java2Blog

Một lần nữa, bạn phải chỉ định cùng một định dạng mã hóa đã được sử dụng trong khi tạo bytearray từ chuỗi. Nếu không, bạn sẽ nhận được đầu ra không mong muốn như hình dưới đây.

myString="Java2Blog"="Java2Blog"

byteArrayObject=bytearray(myString,'utf-8')=bytearray(myString,'utf-8')

in ("Chuỗi đầu vào là:", MyString)("The input string is:",myString)

in ("đối tượng bytearray là:", bytearrayobject)("The bytearray object is:",byteArrayObject)

output_string=byteArrayObject.decode('utf-16')=byteArrayObject.decode('utf-16')

in ("Chuỗi đầu ra là:", output_string)("The output string is:",output_string)

Output:

Chuỗi đầu vào: java2bloginput stringis:Java2Blog

Đối tượng bytearray: bytearray (b'java2blog ')bytearray objectis:bytearray(b'Java2Blog')

Chuỗi đầu ra: java2blog(most recent call last):

  File"/home/aditya1117/PycharmProjects/pythonProject/webscraping.py",line5,inFile"/home/aditya1117/PycharmProjects/pythonProject/webscraping.py",line5,in<module>

    output_string=byteArrayObject.decode('utf-16')output_string= byteArrayObject.decode('utf-16')

UnicodedEcodeError: 'UTF-16-le'Codec không thể sử dụng byte0x67inpocation8: Dữ liệu bị cắt cụt:'utf-16-le'codec can'tdecode byte0x67inposition8:truncated data

Một lần nữa, bạn phải chỉ định cùng một định dạng mã hóa đã được sử dụng trong khi tạo bytearray từ chuỗi. Nếu không, bạn sẽ nhận được đầu ra không mong muốn như hình dưới đây.

Traceback (cuộc gọi gần đây nhất cuối cùng):

Sử dụng mô -đun codecs để chuyển đổi bytearray thành chuỗi trong python

Việc triển khai hàm

PY3K = sys.version_info >= (3, 0)

lines = []
for line in stream:
    if not PY3K:
        lines.append(line)
    else:
        lines.append(line.decode('utf-8', 'backslashreplace'))
7 cũng được đưa ra trong mô -đun
# --- preparation

import codecs

def slashescape(err):
    """ codecs error handler. err is UnicodeDecode instance. return
    a tuple with a replacement for the unencodable part of the input
    and a position where encoding should continue"""
    #print err, dir(err), err.start, err.end, err.object[:err.start]
    thebyte = err.object[err.start:err.end]
    repl = u'\\x'+hex(ord(thebyte))[2:]
    return (repl, err.end)

codecs.register_error('slashescape', slashescape)

# --- processing

stream = [b'\x80abc']

lines = []
for line in stream:
    lines.append(line.decode('utf-8', 'slashescape'))
1. Bạn cũng có thể sử dụng hàm
PY3K = sys.version_info >= (3, 0)

lines = []
for line in stream:
    if not PY3K:
        lines.append(line)
    else:
        lines.append(line.decode('utf-8', 'backslashreplace'))
7 được xác định trong mô -đun
# --- preparation

import codecs

def slashescape(err):
    """ codecs error handler. err is UnicodeDecode instance. return
    a tuple with a replacement for the unencodable part of the input
    and a position where encoding should continue"""
    #print err, dir(err), err.start, err.end, err.object[:err.start]
    thebyte = err.object[err.start:err.end]
    repl = u'\\x'+hex(ord(thebyte))[2:]
    return (repl, err.end)

codecs.register_error('slashescape', slashescape)

# --- processing

stream = [b'\x80abc']

lines = []
for line in stream:
    lines.append(line.decode('utf-8', 'slashescape'))
1 để chuyển đổi bytearray thành một chuỗi trong Python.codecs

myString="Java2Blog"="Java2Blog"

byteArrayObject=bytearray(myString,'utf-8')=bytearray(myString,'utf-8')

in ("Chuỗi đầu vào là:", MyString)("The input string is:",myString)

in ("đối tượng bytearray là:", bytearrayobject)("The bytearray object is:",byteArrayObject)

output_string=codecs.decode(byteArrayObject,'utf-8')=codecs.decode(byteArrayObject,'utf-8')

in ("Chuỗi đầu ra là:", output_string)("The output string is:",output_string)

Output:

Chuỗi đầu vào: java2bloginput stringis:Java2Blog

Đối tượng bytearray: bytearray (b'java2blog ')bytearray objectis:bytearray(b'Java2Blog')

Chuỗi đầu ra: java2blogoutput stringis:Java2Blog

Một lần nữa, bạn phải chỉ định cùng một định dạng mã hóa đã được sử dụng trong khi tạo bytearray từ chuỗi. Nếu không, bạn sẽ nhận được đầu ra không mong muốn như hình dưới đây.

Traceback (cuộc gọi gần đây nhất cuối cùng):

Sử dụng mô -đun codecs để chuyển đổi bytearray thành chuỗi trong python

Việc triển khai hàm

PY3K = sys.version_info >= (3, 0)

lines = []
for line in stream:
    if not PY3K:
        lines.append(line)
    else:
        lines.append(line.decode('utf-8', 'backslashreplace'))
7 cũng được đưa ra trong mô -đun
# --- preparation

import codecs

def slashescape(err):
    """ codecs error handler. err is UnicodeDecode instance. return
    a tuple with a replacement for the unencodable part of the input
    and a position where encoding should continue"""
    #print err, dir(err), err.start, err.end, err.object[:err.start]
    thebyte = err.object[err.start:err.end]
    repl = u'\\x'+hex(ord(thebyte))[2:]
    return (repl, err.end)

codecs.register_error('slashescape', slashescape)

# --- processing

stream = [b'\x80abc']

lines = []
for line in stream:
    lines.append(line.decode('utf-8', 'slashescape'))
1. Bạn cũng có thể sử dụng hàm
PY3K = sys.version_info >= (3, 0)

lines = []
for line in stream:
    if not PY3K:
        lines.append(line)
    else:
        lines.append(line.decode('utf-8', 'backslashreplace'))
7 được xác định trong mô -đun
# --- preparation

import codecs

def slashescape(err):
    """ codecs error handler. err is UnicodeDecode instance. return
    a tuple with a replacement for the unencodable part of the input
    and a position where encoding should continue"""
    #print err, dir(err), err.start, err.end, err.object[:err.start]
    thebyte = err.object[err.start:err.end]
    repl = u'\\x'+hex(ord(thebyte))[2:]
    return (repl, err.end)

codecs.register_error('slashescape', slashescape)

# --- processing

stream = [b'\x80abc']

lines = []
for line in stream:
    lines.append(line.decode('utf-8', 'slashescape'))
1 để chuyển đổi bytearray thành một chuỗi trong Python.

Mảng byte có thể được chuyển đổi thành chuỗi không?

Có hai cách để chuyển đổi mảng byte thành chuỗi: bằng cách sử dụng trình xây dựng lớp chuỗi.Bằng cách sử dụng mã hóa UTF-8.By using String class constructor. By using UTF-8 encoding.

Chúng ta có thể chuyển đổi mảng thành chuỗi trong python không?

Để chuyển đổi danh sách thành một chuỗi, hãy sử dụng khả năng hiểu danh sách Python và hàm tham gia ().Sự hiểu biết danh sách sẽ đi qua từng phần tử một và phương thức tham gia () sẽ kết hợp các phần tử của danh sách thành một chuỗi mới và trả về nó làm đầu ra.use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.

Là byte [] giống như chuỗi?

Các đối tượng byte là chuỗi byte, trong khi các chuỗi là chuỗi các ký tự.Các đối tượng byte ở dạng máy có thể đọc được nội bộ, các chuỗi chỉ ở dạng người có thể đọc được.Vì các đối tượng byte có thể đọc được máy, chúng có thể được lưu trữ trực tiếp trên đĩa.. Byte objects are in machine readable form internally, Strings are only in human readable form. Since Byte objects are machine readable, they can be directly stored on the disk.

Phương pháp nào chuyển đổi dữ liệu byte thô thành chuỗi trong python?

Sử dụng phương thức decode () python cung cấp phương thức decode () tích hợp, được sử dụng để chuyển đổi byte thành một chuỗi.decode() method Python provides the built-in decode() method, which is used to convert bytes to a string.