繁体   English   中英

如何使用python用列表中的几个数字替换文本文件中的字符串?

[英]How to substitute string in a text file with a couple of numbers in a list using python?

例如,有一个列表lst = [2,4,6,8,10]和一个包含“ h = 1”的文本文件,我想将1更改为lst中的数字,并保留其余部分该文本保持不变,自动保存在单独的文本文件中。 我使用.replace('h = 1','h = 2')....写了一个哑巴。但是,当涉及大量内容时,由于我必须手动对其进行编辑,因此它不起作用。 如何实现随机输入列表提供的功能,文本文件可以替换为列表中的值?

使用str.format()。 {}是字符串中的通配符。 '{} is the number {}'.format('one', 1)返回字符串'one is the number 1'

file_name = 'the_file_{}.txt'
my_list = [2, 3, 4, 5, 6]
for num in my_list:
    new_file = open(file_name.format(num), 'w')
    new_text = big_text_string.replace('h=1', 'h={}'.format(num))
    new_file.write(new_text)
    new_file.close()

您可以编写一个将列表作为变量的函数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM