如何在 Python 中创建其中包含变量的变量字符串?

How can one create variable strings with variables inside them in Python?

我想向某些学习小组发送预定义的消息,其中包含有关 类、日期和要学习的单元的信息,同时只更改一些小的事情。为此,我创建了三个列表,如下所示:

classes = ['Math', 'English', 'History']
units = ['Unit 9', 'Unit 10', 'the Exam']
dates = ['may 11th', 'may 18th', 'may 25th']

为了调用每个列表项,我使用了 for 语句(下面的最小示例):

for j in range(len(classes)):
    for i in range(len(units)):
        text = ''' Hello, we'll have %s classes on %s.
        The topic will be %s.
        ''' % (classes[j], dates[i], units[i])
        print(text)

此代码为每个组打印我想要的消息。但是,我不知道如何将这些文本中的每一个关联到一个 不同的 变量,以便稍后在我告诉我的代码编写每封电子邮件时调用它。

第一个快速样式建议 - 而不是使用 for 循环生成数字索引

for j in range(len(classes)):
   ...

只需选择一个有意义的循环变量(例如 classname),然后使用 for 循环遍历列表中的循环变量:

for classname in classes:
    ...

对于您的 unitsdates 列表,您将在其中“并行”处理它们,这是 zip( ) 函数的经典用法,其中 'zips' 这两个函数一起列出并创建一个元组的虚拟列表,然后您可以使用 for 循环遍历 two 循环变量并行处理两个值

for unit, date in zip(units, dates):
    ...

结合这些更改,您将拥有有意义的变量名称(classnameunitdate

最后,为了 'plug in' 您的变量,一种称为 f-strings 的最新方法允许您创建带有占位符的字符串。占位符可以包含 any 有效的 Python 表达式,它将被计算并插入到更大的字符串中

例如:

name = "Fred"
age = 12

# f-string starts with f then a quote character
# anything inside curly braces  {  }  is evaluated as a
# Python expression and substituted as text into the larger string

text = f"{name} is {age + 1} years old on his next birthday"

然后最后将每个字符串添加到不同的变量中,您可以按照海报 RufusVS 的建议将每个字符串附加到列表中。这将允许您通过数字引用每个字符串。

如果你真的希望每个字符串都有一个全新的变量名,你可以做一些更多的元数据并通过写入全局符号为每个字符串创建一个新变量table 这只是 Python 用来跟踪其全局变量的字典。

这是将每条消息附加到列表的方法:

classes = ['Math', 'English', 'History']
units = ['Unit 9', 'Unit 10', 'the Exam']
dates = ['may 11th', 'may 18th', 'may 25th']

all_messages = []     # empty list for the messages

for classname in classes:
    for unit, date in zip(units, dates):
        string = (f"Hello, we'll have {classname} class on {date}\n"
                + f"The topic will be {unit}\n")
        print(string)                   # for debugging
        all_messages.append(string)     # to save each message

print(Message 5 is", all_messages[5])
    

这是一种更元的方法,您实际上可以在其中创建消息形式的新变量n(例如message0message1) 对于您创建的每条消息

classes = ['Math', 'English', 'History']
units = ['Unit 9', 'Unit 10', 'the Exam']
dates = ['may 11th', 'may 18th', 'may 25th']

symbol_table = globals()    # get the global symbol table
count = 0                   # counter to track which message variable we are creating

for classname in classes:
    for unit, date in zip(units, dates):
        string = (f"Hello, we'll have {classname} class on {date}\n"
                + f"The topic will be {unit}\n")
        print(string)                   # for debugging
    
    # little tricky here - create a string with the name of the
    # variable you want to create (eg. 'message5')
    # then use that string as the key in the globals dictionary
    # the value associated with that key is the new message
    # this actually creates a new global variable for each message
    
        symbol_table[f"message{count}"] = string
        count += 1
    
print("Message 5 is", message5)