Home > Blockchain >  Convert unicode to decimal
Convert unicode to decimal

Time:11-08

I have a string like this which i want to convert to only decimal data:

"\u0006;\u0003\u001588D402"

I'm not sure what the output should look like, but I imagine it should be like this:

"631588D402"

I have tried to separate each hexadecimal data and then join them but have been unable to either separate them or convert them correctly. Any idea?

CodePudding user response:

you can go through the string and if the current char is a hex number you add it to new_s elif char in string.printable you skip it (because it is not a hex number and it is printable so it's not some value) else you convert char to his value and then to hex and add the hex value to new_s

import string


s = "\u0006;\u0003\u001588D402"
new_s = ""
for char in s:
    if char in "0123456789ABCDEF":  # if char is a hex number
        new_s  = char
    # the char isn't a hex number and is printable (removes ;)
    elif char in string.printable:
        pass
    else:
        new_s  = hex(ord(char))[2:]
# in one line:
# new_s = "".join([char if char in "0123456789ABCDEF" else "" if char in string.printable else hex(ord(char))[2:] for char in s])
print(new_s)

  • Related