【问题标题】:How to call a list in a string?如何调用字符串中的列表?
【发布时间】:2021-07-03 16:00:19
【问题描述】:

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


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


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

我希望我的doc_up 使用列表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

【问题讨论】:

标签: python string


【解决方案1】:

您可以使用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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-10
    • 1970-01-01
    • 2014-11-06
    • 1970-01-01
    • 1970-01-01
    • 2019-05-13
    • 2012-10-23
    • 1970-01-01
    相关资源
    最近更新 更多