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?

2 Answers 2

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']
Sign up to request clarification or add additional context in comments.

Comments

4

Assuming words are properly separated

[x for x in my_string.split() if x.startswith('0x')]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.