首页 > 解决方案 > 在字符串中查找变量的名称,然后将变量名称替换为变量值

问题描述

我正在尝试在字符串中查找对变量的引用(此处:变量为 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}")

标签: pythonregex

解决方案


这个东西是内置在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}"))

推荐阅读