python - Appending '0x' before the hex numbers in a string -


i'm parsing xml file in basic expressions (like id*10+2). trying evaluate expression value. so, use eval() method works well.

the thing numbers in fact hexadecimal numbers. eval() method work if every hex number prefixed '0x', not find way it, neither find similar question here. how done in clean way ?

use re module.

>>> import re >>> re.sub(r'([\da-f]+)', r'0x\1', 'id*a+2') 'id*0xa+0x2' >>> eval(re.sub(r'([\da-f]+)', r'0x\1', 'cafe+babe')) 99772 

be warned though, invalid input eval, won't work. there many risks of using eval.

if hex numbers have lowercase letters, use this:

>>> re.sub(r'(?<!i)([\da-fa-f]+)', r'0x\1', 'id*a+b') 'id*0xa+0xb' 

this uses negative lookbehind assertion assure letter i not before section trying convert (preventing 'id' turning 'i0xd'. replace i i if variable id.


Comments

Popular posts from this blog

php - Why I am getting the Error "Commands out of sync; you can't run this command now" -

linux - Does gcc have any options to add version info in ELF binary file? -

java - Are there any classes that implement javax.persistence.Parameter<T>? -