1

I have a variable data:

data = [b'script', b'-compiler', b'123cds', b'-algo', b'timing']

I need to convert it to remove all occurrence of "b" in the list. How can i do that?

joaquin
  • 82,968
  • 29
  • 138
  • 152
Ani
  • 918
  • 1
  • 10
  • 25

3 Answers3

4

Not sure whether it would help - but it works with your sample:

initList = [b'script', b'-compiler', b'123cds', b'-algo', b'timing']
resultList = [str(x) for x in initList ]

Or in P3:

resultList = [x.decode("utf-8") for x in initList ] # where utf-8 is encoding used

Check more on decode function.

Also you may want to take a look into the following related SO thread.

Community
  • 1
  • 1
Artsiom Rudzenka
  • 27,895
  • 4
  • 34
  • 52
  • Hey Artsiom, I doesn't work on my end. For your reference, I am running python 3.2.2 on windows. – Ani Nov 10 '11 at 10:21
3
>>> a = [b'script', b'-compiler', b'123cds', b'-algo', b'timing']
>>> map(str, a)
['script', '-compiler', '123cds', '-algo', 'timing']
Dogbert
  • 212,659
  • 41
  • 396
  • 397
  • I am getting following result instead of the formatted list: – Ani Nov 10 '11 at 10:23
  • 1
    Yes, in Python 3 `map` is lazy. If you want to force it to a list use `list(map(str, a))`, but for many purposes you can just use the output from `map` directly and it will convert the individual elements as they are needed. – Duncan Nov 10 '11 at 10:50
1
strin = "[b'script', b'-compiler', b'123cds', b'-algo', b'timing']"
arr = strin.strip('[]').split(', ')
res = [part.strip("b'") for part in arr]

>>> res
['script', '-compiler', '123cds', '-algo', 'timing']
egor83
  • 1,199
  • 1
  • 13
  • 26
  • thank you for your reply, but I am getting the following error " arr = data1.strip('[]').split(', ') AttributeError: 'list' object has no attribute 'strip' – Ani Nov 10 '11 at 10:18
  • This example works with `strin = "[b'script', b'-compiler', b'123cds', b'-algo', b'timing']"`, which is a string, not a list. – glglgl Nov 10 '11 at 10:22