[英]How should I add quote to it which match using python re?
我有一個字符串,像這樣:
{"content":(uint64)123456, "id":(uint32)0}
注意:
此示例字符串很簡單,實際字符串為JSON,但(uint32)0
不是標准字符串。
現在,我需要像這樣轉換它:
{"content":"(uint64)123456", "id":"(uint32)0"}
所以,我用python re編寫了轉換代碼:
def format():
pattern = re.compile(r'(\(uint32\)|\(int32\)|\(uint64\)|\(int64\))(\d)+')
print pattern.sub('\"test\"', '{"content":(uint64)123456, "id":(uint32)0}')
我應該如何在sub
編寫代碼以使其變形?
sub
代替字符串也可以接受可調用對象作為替換。
因此,代替:
pattern.sub('\"test\"', s)
做一個功能:
def add_quotes(match):
return '"%s"' % match.group(0)
pattern.sub(add_quotes, s)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.