我有一个像这样的字符串 -
str = 'some_random_command_that_take_parameters -d{"key1": "value1", "key2": "value2", "key3": "value3", "tableName": "my_table", "key5": "value5", "key6":"value6"}'
我需要搜索" tableName":" my_table"并将其替换为" tableName":" my_table_temp"在python中。
值" my_table"是可变的,我在编码时不知道它。所以我不能只搜索它并替换它。我唯一可以搜索的是" tableName" (或任何其他钥匙)。
编辑: 很抱歉不清楚,示例不是字典,整个事情都是字符串。
答案 0 :(得分:2)
作为字符串:
s = '{"key1": "value1", "key2": "value2", "key3": "value3",' + \
' "tableName": "my_table", "key5": "value5", "key6":"value6"}'
# using regular expressions
# (quick and dirty)
import re
s = re.sub(
'(?<="tableName":)\s*"(.*?)"',
lambda match: ' "{}_temp"'.format(match.group(1)),
s
)
# OR
# using ast.literal_eval
# (less efficient but more bomb-proof)
import ast
d = ast.literal_eval(s) # parse to dict
d["tableName"] = d["tableName"] + "_temp" # update field
s = str(d) # cast back to string