3

I want to extract hexadecimal number from a string. For example, the string is: OxDB52 Message 1 of orderid 1504505254 for number +447123456789 rejected by Operator. I want to extract hexadecimal OxDB52 part. I know it can be done checking for 0x in string.

But is there any cool pythonic way to extract hexadecimal number from string?

user
  • 5,335
  • 7
  • 47
  • 63

2 Answers2

8

You can use regex pattern with re.findall() method:

re.findall(r'0x[0-9A-F]+', your_string, re.I)

this will give you a list of all the hexadecimal numbers in your_string.

Demo:

>>> s = '0xDB52 Message 0x124A orderid 1504505254 for number 0xae45'
>>> re.findall(r'0x[0-9A-F]+', s, re.I)
['0xDB52', '0x124A', '0xae45']
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
4

Assuming words are properly separated

[x for x in my_string.split() if x.startswith('0x')]
RedBaron
  • 4,717
  • 5
  • 41
  • 65