Convert list of bytes strings to single string in Python

The bytes.join command converts list of bytes strings to a single ASCII string. Imagine in.dat is binary data with an ASCII header, so common to legacy code.

from pathlib import Path
infn = Path('in.dat')

with infn.open('rb') as f:
    line = f.readline().split()
    dat = line[-5:]
    header = line[:6]

    txt = bytes.join(b' ', header).decode('ascii')

where header was

[b'this', b'is', b'a', b'yucky', b'ascii', b'header']

Categories:

Updated:

Leave a Comment