Convert bytes into list - python

I am new to this sort of stuff, so sorry if it's really simple and I am just being stupid.
So I have this variable with some bytes in it (not sure if that's the right name.)
data = b'red\x00XY\x001\x00168.93\x00859.07\x00'
I need to convert this to a list. The intended output would be something like.
["red","XY","1","169.93","859.07"]
How would I go about doing this?
Thank you for your help.

We can use the following line:
[x.decode("utf8") for x in data.split(b"\x00") if len(x)]
Going part by part:
x.decode("utf8"): x will be a bytes string, so we need to convert it into a string via `.decode("utf8").
for x in data.split(b"\x00"): We can use python's built in bytes.split method in order to split the byte string by the nullbytes to get an array of individual strings.
if len(x): This is equivalent to if len(x) > 0, since we want to discard the empty string at the end.

This code may help you to understand if you want exact same output using the pop() function.
data = 'red/x00XY/x001/x00168.93/x00859.07/x00' # I change "/" mark from "\" because i'm using Linux otherwise it will give error in Linux
new_list = [] # There is a variable that contain empty list
for item in data.split('/x00'): # Here I use split function by default it splits variable where "," appears but in this case
new_list.append(item) # you need list should be separated by "/" so that's why I gave split('/x00') and one by list appended
print(new_list)

Related

How to get first n charakters of a string AND the last one?

I got this code which does something with the first 10 charakters of a string:
f_binary = f.encode(encoding='utf_8')[0:10]
but I want to do it with the 19th charakter as well. I tried like this:
f_binary = f.encode(encoding='utf_8')[0:10],[19]
and this:
f_binary = f.encode(encoding='utf_8')[0:10,19] but it doesn't work.
Python's list comprehension doesn't help me either because it doesn't show how to deal with a larger and a small part of a list or string at the same time.
Just use
f_binary = (f[0:10]+f[-1]).encode(encoding='utf_8')
to encode the first 10 and the last character of string f
turn it to a string and then select using
first_n_chars_and_last = (f[0:n], f[-1])
and turn it THEN into a bytes object

Using pop on a list containing a string

I have a list:
listA = ['1,2,3,4,5']
where it is in string format. I want to perform a simple function that removes the last digit in the string, which in this case would be 5 and print it out.
I've tried something
listA = ['1,2,3,4,5']
for i in listA:
print(listA.pop())
What i tried is wrong as I'm not familiar with using pop on strings.
What you have is not a list of integers. It is a list with a single element, that element is a string of comma separated integers
You're not using i
You're iterating over the list and mutating it as you do so. Do not do this, because it does not give you the behaviour you expect.
I would recommend a while loop instead. First, fix your array.
listA = listA[0].split(',')
Now, iterate over it.
while listA:
print(listA.pop())
You use the truthiness of a nonempty list to keep iterating over it. This removes all the digits. However, if you just want the last digit and nothing more, call listA.pop() only once.
If you don't want to fix your array, you should extract the last digit like this:
listA = ['1,2,3,4,5']
print(int(listA[0][-1])) # [0] gets the string, [-1] gets the last character in the string
This is ungainly, so I recommend fixing your array instead.
The previous answer is giving you the last character. You can also extract the last value using split which will break up text based on a defined delimiter:
listA = ['1,2,3,4,5']
print( listA[0].split(',')[-1] )

How do I pop() elements inside the list in python2.7

I just want to ask if how should I pop certain elements inside the list.
Let's say I have this list:
c = ['123','456','789']
When I type this:
print c[0][0]
It prints a value '1',
And somehow I want to delete the first element of the first value.
So that the output will be:
c = ['23','456','789']
But I have a problem in using pop().
I tried this but no luck:
c.pop(0, 0) # takes only one argument
Or
c[0].pop(0) # string doesn't have an attribute pop
Is there a way to solve my dilemma?
If this problem has a duplicate, please let me know.
Strings are immutable. As such, they can't be modified once created.
If all you want to do is "remove" the first character of the first string in the list c you can use slicing (that returns a new string):
c[0] = c[0][1:]
Read more on slicing here: Explain Python's slice notation

Splitting up a list with all values sitting in the same index in Python

Im pretty new to Python.
I have a list which looks like the following:
list = [('foo,bar,bash',)]
I grabbed it from and sql table (someone created the most rubbish sql table!), and I cant adjust it. This is literally the only format I can pull it in. I need to chop it up. I can't split it by index:
print list[0]
because that just literally gives me:
[('foo,bar,bash',)]
How can I split this up? I want to split it up and write it into another list.
Thank you.
list = [('foo,bar,bash',)] is a list which contains a tuple with 1 element. You should also use a different variable name instead of list because list is a python built in.
You can split that one element using split:
lst = [('foo,bar,bash',)]
print lst[0][0].split(',')
Output:
['foo', 'bar', 'bash']
If the tuple contains more than one element, you can loop through it:
lst = [('foo,bar,bash','1,2,3')]
for i in lst[0]:
print i.split(',')

Swapping pairs of characters in a string

Okay, I'm really new to Python and have no idea how to do this:
I need to take a string, say 'ABAB__AB', convert it to a list, and then take the leading index of the pair I want to move and swap that pair with the __. I think the output should look something like this:
move_chars('ABAB__AB', 0)
'__ABABAB'
and another example:
move_chars('__ABABAB', 3)
'BAA__BAB'
Honestly have no idea how to do it.
Python strings are immutable, so you can't really modify a string. Instead, you make a new string.
If you want to be able to modify individual characters in a string, you can convert it to a list of characters, work on it, then join the list back into a string.
chars = list(str)
# work on the list of characters
# for example swap first two
chars[0], chars[1] = chars[1], chars[0]
return ''.join(chars)
I think this should go to the comment section, but I can't comment because of lack of reputation, so...
You'll probably want to stick with list index swapping, rather than using .pop() and .append(). .pop() can remove elements from arbitrary index, but only one at once, and .append() can only add to the end of the list. So they're quite limited, and it would complicate your code to use them in this kind of problems.
So, well, better stick with swapping with index.
The trick is to use list slicing to move parts of the string.
def move_chars(s, index):
to_index = s.find('__') # index of destination underscores
chars = list(s) # make mutable list
to_move = chars[index:index+2] # grab chars to move
chars[index:index+2] = '__' # replace with underscores
chars[to_index:to_index+2] = to_move # replace underscores with chars
return ''.join(chars) # stitch it all back together
print(move_chars('ABAB__AB', 0))
print(move_chars('__ABABAB', 3))

Categories

Resources