首页 > 解决方案 > 如何调用字符串中的列表?

问题描述

我是 python 编程的新手,并试图在编辑字符串文件时了解它是如何工作的。我想在字符串中调用变量或列表或元组并求解值并更新字符串文件。这是一个简单的例子


t_list = ['c','d','e']


doc = '''
 domain ()
 :types a b c - objects
        f"{t_list}" - items
'''
doc_up = doc

我希望doc_up用 list 的值更新我的值t_list。我提到了PEP 498: Formatted string literals但它不起作用。

我的输出是这样的:

'\n domain ()\n :types a b c - objects\n        f"{t_list}" - items\n'

我希望我的输出是这样的:

 domain ()
 :types a b c - objects
        c d e - items

标签: pythonstring

解决方案


您可以使用str.format. f"..."从字符串中删除并仅保留,{t_list}例如:

t_list = ["c", "d", "e"]


doc = """
 domain ()
 :types a b c - objects
        {t_list} - items
"""

doc_up = doc.format(t_list=" ".join(t_list))
print(doc_up)

印刷:


 domain ()
 :types a b c - objects
        c d e - items


推荐阅读