3

I have a data.txt file with the following lines:

this is sample {data1}
this one is {data2}
again {data1}

And I have this code to read the file's lines into a list and print the list:

    data1 = 'line 1'
    data2 = 'line 2'

    with open('data.txt') as file:
        lines = file.read().splitlines()

    print(lines)

The output is:

['this is sample {data1}', 'this one is {data2}', 'again {data1}']

Now, How can I replace the variables with their value and have it like:

['this is sample line 1', 'this one is line 2', 'again line 1']

1 Answer 1

2

Put the replacements in a dictionary, then call format().

values = {'data1': 'line 1', 'data2': 'line 2'}
print([line.format(**values) for line in lines])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.