简体   繁体   中英

How do I convert a list of byte literals into string literals in python 3?

I have a list of byte literals:

list1 = [b'R103', b'R102', b'R109', b'R103']

I would like to convert this list of byte literals into string literals. So something like:

list1 = ['R103', 'R102', 'R109', 'R103']

I have tried using decode:

list1.decode("UTF-8")

But, decode does not work for lists. I end up with the following error message:

AttributeError: 'list' object has no attribute 'decode'

Is there a way to convert the entire list to string literals that I am missing?

As mentioned in the comments, you want to use list comprehension. In your code example you were trying to apply the function decode() on the whole list, as opposed to the elements of that list. In the below, list2 is defined by iterating over the elements of list1 , and converting applying decode() to each element, and then creating a new list out of the elements and assigning them to list2

In [1]: list1 = [b'R103', b'R102', b'R109', b'R103']

In [2]: list2 = [x.decode("UTF-8") for x in list1]

In [3]: list2
Out[3]: ['R103', 'R102', 'R109', 'R103']

Hope this makes sense!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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