在字符串中查找变量的名称,然后将变量名称替换为变量值

时间:2019-03-20 22:02:04

标签: python regex

我试图在字符串中找到对变量的引用(此处:变量为var1)

我想在句子中找到{var1}并将其替换为var1(“ testentry1”)的值

引用var1可以设置所需的字符串

但是,在引用var_name时我不能做同样的事情

我将有许多变量名(例如{var1}{var2},这些变量名将用句子表达,我想用一种方法将适当的单词替换为字符串。

class TestClass:
    def __init__(self):
        self.var1 = "testentry1"
        self.var2 = "testentry2"


    def convert_text(self, original_text):
        #find the variable name of interest (here: {var1})
        found_text = re.findall('\{([^{}]*)\}', original_text)
        var_name = found_text[0]
        #replace {var1} with the value for var1
        search_str = "{"+var_name+"}"
        new_text = original_text.replace(search_str, self.var_name)
        new_text2 = original_text.replace(search_str, self.var1)

        print("output1 is (not desired result):", new_text)
        print("output2 is (desired result):", new_text2)
        return new_text2

TC = TestClass()



TC.convert_text("this is the text to change {var1}")
TC.convert_text("this is the text to change {var2}")

1 个答案:

答案 0 :(得分:2)

这些东西是内置在python中的:

var1 = "testentry1"
print("this is the text to change {var1}".format(**locals()))

请注意,通常最好使用字典来承载上下文,而不要使用裸变量。

如果您的字符串是静态的(也就是说,您在事先知道所有变量的上下文中使用它们),则只需在字符串前面加上f(python 3.6 +):

var1 = "testentry1"
print(f"this is the text to change {var1}")

如果您确实真的想重新发明轮子,也可以使用re's做同样的事情:

def my_format(s, vars):
    return re.sub(r'{(\w+)}', lambda m: vars[m.group(1)], s)


print(my_format("this is the text to change {var1}", locals()))

也可以使用“自动”替换上下文外(非本地)变量,但是这种方式很不客气:

# do NOT do that!

import re
import sys

var1 = "testentry1"


def my_format2(s):
    return re.sub(r'{(\w+)}', lambda m: eval(m.group(1)), s)


def get_var(name):
    f = sys._getframe()
    while f:
        if name in f.f_locals:
            return f.f_locals[name]
        f = f.f_back


def my_format3(s):
    return re.sub(r'{(\w+)}', lambda m: get_var(m.group(1)), s)


print(my_format2("this is the text to change {var1}"))
print(my_format3("this is the text to change {var1}"))

为响应您的更新,可以将format与dict类一起使用:

class TestClass:
    def __init__(self):
        self.var1 = "testentry1"
        self.var2 = "testentry2"

    def convert_text(self, original_text):
        return original_text.format(**vars(self))


TC = TestClass()

print(TC.convert_text("this is the text to change {var1}"))
print(TC.convert_text("this is the text to change {var2}"))