简体   繁体   English

Python替换包含十六进制数字的子字符串

[英]Python replace sub string containing hex digit

如何在python中用新的十六进制值替换子字符串值(十六进制值0x20E00)?

 <d:var name="Length" value="0x20E00"/>

You could use a regular expression and re.sub() : 您可以使用正则表达式和re.sub()

>>> import re
>>> s = '<d:var name="Length" value="0x20E00"/>'
>>> re.sub(r'0[xX][0-9a-fA-F]+', '0xdeadbeef', s)
'<d:var name="Length" value="0xdeadbeef"/>'

That said, if you're working with XML, you're much better off using an XML parser to manipulate it. 就是说,如果您正在使用XML,那么最好使用XML解析器来操作它。

Here's a way using re.sub with look behind : 这是在look behind使用re.sub的方法:

re.sub(r'(?<=value=\").*(?=\")', 'new hex value',s)
'<d:var name="Length" value="new hex value"/>'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM