python - 如何调用字符串中的列表?
问题描述
我是 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
解决方案
您可以使用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
推荐阅读
- c++ - 如何在 C++ 中从具有不同行大小的文件中读取一行?
- postgresql - 如何从两个不同的表中获取最近城市的距离并将其组合到 PostgreSQL 中的 1 列中
- javascript - 使用 jQuery 打开仅 CSS 的模型弹出窗口
- facebook-graph-api - 如何从 instagram 获得总评论数、参与度、每周帖子数?
- bash - bash 脚本内 $0 的意外值
- go - Flutter IAP 支付验证和消耗品
- android - 在 Flutter Project 中 Android 项目屏幕自动打开
- reactjs - React+ 将整个状态对象发送到另一个组件
- python - Python:一组输出的顺序
- git - 如何在 Fork 中将更改视图设置为默认值?