Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/285.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 替换与dict中的键匹配的字符串中的项_Python_String_Python 2.7_Replace - Fatal编程技术网

Python 替换与dict中的键匹配的字符串中的项

Python 替换与dict中的键匹配的字符串中的项,python,string,python-2.7,replace,Python,String,Python 2.7,Replace,我试图用dict中的键替换SQL查询字符串中的字符,而不是“[low\u level\u rand\u num]”=“[rand\u num]”: replacements = { '"[low_level_rand_num]"': str(random.randint(1, 13)), '"[rand_num]"': str(random.randint(13, 26)), '"[comment]"': random.choice(["--", "/*", "#", "

我试图用dict中的键替换SQL查询字符串
中的字符,而不是“[low\u level\u rand\u num]”=“[rand\u num]”

replacements = {
    '"[low_level_rand_num]"': str(random.randint(1, 13)),
    '"[rand_num]"': str(random.randint(13, 26)),
    '"[comment]"': random.choice(["--", "/*", "#", "*/", "'", '"', "`", "-"]),
    '"[rand_string]"': "asdf",
    '"[query]"': "test_col",
    '"[big_int_1]"': str(random.randint(10000000000, 99999999999)),
    '"[big_int_2]"': str(random.randint(10000000000, 99999999999)),
    '"[encoding]"': random.choice(["utf8", "utf16", "utf32", "ascii"]),
    '"[sleeper]"': str(random.randint(3, 9))
}
像这样使用
string.replace()
函数:

def build_payloads(template):
    replacements = {
        '"[low_level_rand_num]"': str(random.randint(1, 13)),
        '"[rand_num]"': str(random.randint(13, 26)),
        '"[comment]"': random.choice(["--", "/*", "#", "*/", "'", '"', "`", "-"]),
        '"[rand_string]"': rand_string_gen(),
        '"[query]"': random_column(),
        '"[big_int_1]"': str(random.randint(10000000000, 99999999999)),
        '"[big_int_2]"': str(random.randint(10000000000, 99999999999)),
        '"[encoding]"': random.choice(["utf8", "utf16", "utf32", "ascii"]),
        '"[sleeper]"': str(random.randint(3, 9))
    }
    for k in replacements.keys():
        if k in template:
            print template.replace(k, replacements[k])
但是,每次运行此函数时,我都会得到以下输出:

OR NOT 7="[rand_num]"
OR NOT "[low_level_rand_num]"=21

它似乎是在替换字符串,但它没有保持替换状态,我在哪里做的不对,字符串将不会一直被替换,我如何解决此问题,并获得预期的
输出或不是7=21

字符串替换未到位,请在替换后更新模板:

...
for k in replacements:
    if k in template:
        template = template.replace(k, replacements[k])
        print template

作为补充说明,在迭代字典键时,您可以删除
。键调用,因为直接迭代字典将运行其键。

您只是输出替换的结果,
模板本身不会更改

template = "foo"
print template.replace("foo","bar") #outputs 'bar'
print template #outputs 'foo'
template = template.replace("foo","bar")
print template #outputs 'bar'
->
返回一个字符串副本,其中所有出现的子字符串old都被new替换。
您需要将字符串替换为str.replace的结果