社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

将文件读入列表并用python中的值替换变量

Kourosh Nomanpour • 5 年前 • 1279 次点击  

this is sample {data1}
this one is {data2}
again {data1}

我有这段代码可以将文件行读入列表并打印列表:

    data1 = 'line 1'
    data2 = 'line 2'

    with open('data.txt') as file:
        lines = file.read().splitlines()

    print(lines)

输出为:

['this is sample {data1}', 'this one is {data2}', 'again {data1}']

现在,我如何用变量的值替换变量,并使其像:

['this is sample line 1', 'this one is line 2', 'again line 1']
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/39577
 
1279 次点击  
文章 [ 1 ]  |  最新文章 5 年前
Barmar
Reply   •   1 楼
Barmar    5 年前

把替换词放到字典里,然后打电话给 format() .

values = {'data1': 'line 1', 'data2': 'line 2'}
print([line.format(**values) for line in lines])