[英]How can I use %s to replace text within a file in python?
I've been working on a project where I open and read a file and replace its text with input, this is what I have been trying to do to put certain words in,我一直在做一个项目,在这个项目中我打开并读取一个文件并用输入替换它的文本,这就是我一直在尝试做的来输入某些单词,
for i in range(0, length):
finallib = str(picks[choice]) % (picked[i])
where length is the length - 1 of the list 'picked' and picked is a list of words.其中 length 是长度 - 'picked' 列表的 1 和 pick 是一个单词列表。 'picks[choice]' is the selection of text from the file that the user chooses to put new words into. 'picks[choice]' 是从文件中选择的文本,用户选择将新词放入其中。 Within the file, The text goes like this 'file text file text file text %s file text file text file text', and I get the error that there are not enough arguments for format string.在文件中,文本类似于“文件文本文件文本文件文本 %s 文件文本文件文本文件文本”,并且我收到错误,提示格式字符串参数不足。 How can I get it to replace what I want it to?我怎样才能让它取代我想要的?
PS the substitution doesn't go into another file or the same file, it is put into a variable that is displayed after it is calculated. PS替换不会进入另一个文件或同一个文件,它被放入一个变量中,在计算后显示。
Why not just use format()
?为什么不直接使用format()
?
for i in range(length): # range automatically starts at 0
finallib = '{} % {}'.format(picks[choice],picked[i])
Or cleaner (list comprehension):或者更清洁(列表理解):
finallib = ['{} % {}'.format(picks[choice],picked[i]) for i in range(length)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.