How to convert str to hex via python [duplicate] - python

This question already has answers here:
Print a string as hexadecimal bytes
(13 answers)
Closed 7 years ago.
I want to convert string to a hex (decimal),
for example abc to 616263 and so on.
How do I do that?
I have tried:
x= input("Enter string")
x = int(x)
hex(x)
But it is not working.

maybe you are looking for something like:
x.encode("hex")

Related

How to convert bytearray to string in python [duplicate]

This question already has answers here:
How to convert bytearray with non-ASCII bytes to string in python?
(4 answers)
Closed 4 years ago.
I need to convert the next bytearray to string:
Num = bytearray()
I have tried
Num = bytearray(str)
but that's not the solution
As t.m.adam said in the comments, use bytearray.decode
b = bytearray("test", encoding="utf-8")
b.decode()
#> 'test'

String to Int in Python [duplicate]

This question already has answers here:
Why does map return a map object instead of a list in Python 3?
(4 answers)
Getting a map() to return a list in Python 3.x
(11 answers)
Closed 5 years ago.
How to Convert a string like '123' to int 1,2 and 3 so that I can perform 1+2+3. I am new to python. Can you please help me? I am not able to split the list. I don't think splitting the string will be of any use as there are no delimiters. Can you help me to understand how can this string elements be separated and treated as intergers?
x = "123"
s = 0
for a in x:
s = int(a) + s

Python Binary string to ASCII text [duplicate]

This question already has answers here:
Convert binary to ASCII and vice versa
(8 answers)
Closed 6 years ago.
x = "01100001"
How do i convert this string into ASCII
Expected Result:
print(x.somefunction())
Output: a
Use following one liner
x = chr(int('010101010',2))
will work.

How to get ACSII value of an integer in python? [duplicate]

This question already has answers here:
Convert int to ASCII and back in Python
(6 answers)
How can I read inputs as numbers?
(10 answers)
Closed 7 years ago.
I have something like this right now but this wont work because chr requires an integer. How can I make it print the chr of the user input?
num1 = input("Enter a ASCII code 0 - 127:")
print(str(chr(num1)))
Just cast the user input to int first -
num1 = input("Enter a ASCII code 0 - 127:")
print chr(int(num1))
(Incorporated #chepner's comment)

Python fastest byte to string conversion [duplicate]

This question already has answers here:
Convert bytes to a string
(22 answers)
Closed 8 years ago.
I need to convert a byte array to a string to send to an SPI device.
Is there a more efficient way of doing this ?
def writebytes(bytes):
str = ""
for i in bytes: str += chr(i)
self.spi.transfer(str)
Use "".join with a generator expression.
def writebytes(bytes):
self.spi.transfer("".join(chr(i) for i in bytes))

Categories