简体   繁体   English

如何使用 %s 替换 python 文件中的文本?

[英]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.

相关问题 如何使用Python替换文件中的大部分文本? - How can I replace a large portion of a text in a file using Python? 我正在使用的当前代码无法将我的文本替换为 .txt 文件中的其他文本,我该如何用 Python 替换它? - The current code I am using is not working to replace my text to other text within a .txt file, how do I replace this with Python? 如何使用str.replace从旋转框获取值,然后在文本文件中替换该值的实例? - How can I use a str.replace to take a value from a spinbox, and then replace an instance of that value in a text file? 如何用 Python 中包含相同数据的单行文本替换文件中的多个 3 行文本块 - How can I replace multiple 3 line blocks of text in a file with a single line of text containing the same data in Python 使用Python在文本文件中查找和替换 - Find and replace within a text file using Python 替换文件Python中的CSS文本块 - Replace CSS block of text within file Python 如何在Windows 10中使用Python 3将文本写入文件 - How can I use Python 3 to write text to a file in Windows 10 如何在文本中用标签的值替换标签 - How to replace tag with it's value within text 如何使用 python 替换文本文件中字段中的值 - How to use python to replace a value in a field in a text file 如何使用 Python 在文本文件中用土耳其语字符替换 Unicode 字符 - How can I replace Unicode characters with Turkish characters in a text file with Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM