Find a hex value in string form in a list of other string types in python

Question:

I have a lists like the following:

['', '', '', 'VALUE', '0x01234', '__INT_S', '0', 'T_DURATION_10', '0', '120n']

I need to look for the hex value 0x01234 in the above string to use it in further processing

I tried

try:
    val = [hex(val) for val in int_vals]

but it didnt work because all the strings lists are a mix of strings integers and hex values.

I guess I could loop through the list and see if the value is hex convertible, but there are a lot of lists and I wanted a less time consuming approach if possible.

Any help would be appreciated

Asked By: Lena Agusty

||

Answers:

You can use the re module to extract the hexadecimal values from the list.

import re

lst = ['', '', '', 'VALUE', '0x01234', '__INT_S', '0', 'T_DURATION_10', '0', '120n']
hex_values = [x for x in lst if re.match(r'0x[0-9a-fA-F]+', x)]
Answered By: Manrique
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.