Home > Backend Development > Python Tutorial > How Can I Convert Bytes to a String in Python 3?

How Can I Convert Bytes to a String in Python 3?

Mary-Kate Olsen
Release: 2025-01-03 16:52:40
Original
880 people have browsed it

How Can I Convert Bytes to a String in Python 3?

Convert Bytes to a String in Python 3

This question arises when handling data captured from external programs or input streams. We want to encode such data as regular Python strings for printing or further processing.

Consider the following bytes object:

>>> from subprocess import *
>>> stdout = Popen(['ls', '-l'], stdout=PIPE).communicate()[0]
>>> stdout
b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar  3 07:03 file1\n-rw-rw-r-- 1 thomas thomas 0 Mar  3 07:03 file2\n'
Copy after login

To convert it to a string for printing purposes, decode the bytes using the appropriate encoding:

>>> stdout.decode("utf-8")
'-rw-rw-r-- 1 thomas thomas 0 Mar  3 07:03 file1\n-rw-rw-r-- 1 thomas thomas 0 Mar  3 07:03 file2\n'
Copy after login

While UTF-8 is a common encoding, it is essential to use the encoding that matches the actual data. Failure to do so may result in garbled or incorrect output.

The above is the detailed content of How Can I Convert Bytes to a String in Python 3?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template