简体   繁体   中英

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. 'picks[choice]' is the selection of text from the file that the user chooses to put new words into. 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. 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.

Why not just use 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)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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