简体   繁体   English

如何在Python3中将字节串列表转换为字符串

[英]How to turn a list of byte-strings into a string in Python3

I have this, via the Github API, after base64 decoding: 在base64解码后,我通过Github API获得了这个:

[b'<!DOCTYPE html>\n', b'<html>\n', b'    <head>\n']

And I'd really like a string (with \\n line endings), or a list of strings. 我真的很喜欢一个字符串(带有\\n行结尾)或字符串列表。

I spent an hour chasing TypeError: a bytes-like object is required, not 'str' because I thought it was already a list of strings, and questioning my own lambda/filter skills before I realized the root cause was somewhere else. 我花了一个小时追逐TypeError: a bytes-like object is required, not 'str'因为我认为它已经是一个字符串列表,并且在我意识到根本原因是在其他地方之前质疑我自己的lambda / filter技能。 I tried googling but I only get hits for 'python bytes to string' which is different. 我尝试使用谷歌搜索,但我只得到'python bytes to string'的命中,这是不同的。

You could just map the bytes.decode method to each element and then join it if you need a single string: 你可以只mapbytes.decode方法给每个元素,然后join它,如果你需要一个字符串:

l = [b'<!DOCTYPE html>\n', b'<html>\n', b'    <head>\n']
s = "".join(map(bytes.decode, l))

or, call decode on each element in a list-comp if you need a list: 或者,如果需要列表,请在list-comp中的每个元素上调用decode

ls = [i.decode() for i in l]

With the results now being: 结果现在是:

>>> print(repr(s))  # repr to show \n 
'<!DOCTYPE html>\n<html>\n    <head>\n'
>>> print(ls)
['<!DOCTYPE html>\n', '<html>\n', '    <head>\n']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM