在python中搜索并替换字符串中的单词

时间:2022-12-27 19:21:39

I have a string like this -

我有这样的字符串 -

str = 'some_random_command_that_take_parameters -d{"key1": "value1", "key2": "value2", "key3": "value3", "tableName": "my_table", "key5": "value5", "key6":"value6"}'

I need to search "tableName": "my_table" and replace it with "tableName": "my_table_temp" in python.

我需要搜索“tableName”:“my_table”并将其替换为“tableName”:python中的“my_table_temp”。

The value "my_table" is variable and I dont know it while codeing. So I can not just search it and replace. The only thing I can search for sure is "tableName" (or any other key).

值“my_table”是可变的,我在编码时不知道它。所以我不能只搜索它并替换它。我唯一可以搜索的是“tableName”(或任何其他键)。

Edit: Sorry for not being clear, the example is not a dictionary, the whole thing is a string.

编辑:抱歉不清楚,示例不是字典,整个事情是一个字符串。

1 个解决方案

#1


2  

As a string:

作为一个字符串:

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

#1


2  

As a string:

作为一个字符串:

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