C
C
che_aa2021-09-15 14:00:43
Python
che_aa, 2021-09-15 14:00:43

How to get bytes from python string?

How can I get a byte code from a string?
Example explaining my situation:

me_string = 'b"some bytes"'
me_string_utf = my_string.encode('utf8') 
# b'b"some bytes"'
# но мне надо чтобы оно выводило b"some bytes"

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alan Gibizov, 2021-09-15
@che_aa

my_string = 'b"some bytes"'
my_string = my_string[2:-1]
me_string_utf = my_string.encode('utf8') 
print(me_string_utf)

It's all right?

V
Vladimir Kuts, 2021-09-15
@fox_12

import re

me_string = 'b"some bytes"'   # нужно понимать что это - строка
result = re.match('^b\"(.*)\"$', me_string).group(1).encode()

print(result)
# b'some bytes'
print(type(result))
# <class 'bytes'>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question