Ben
Ben

Reputation: 21

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?

P.S. 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.

Upvotes: 1

Views: 457

Answers (1)

lbragile
lbragile

Reputation: 8122

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)]

Upvotes: 2

Related Questions