Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

I'm using Python to open a text document:

text_file = open("Output.txt", "w")

text_file.write("Purchase Amount: " 'TotalAmount') text_file.close()

I want to substitute the value of a string variable TotalAmount into the text document. Can someone please let me know how to do this?

1 Answer

0 votes
by (106k points)
edited by

 For the version Python2.6, it's preferred to use str.format()method:-

with open("Output.txt", "w") as text_file: text_file.write("Purchase Amount: {0}".format(TotalAmount))

If you are using Python2.7 and higher versions you can use {} instead of {0} which we have used in Python 2.6:-

with open("Output.txt", "w") as text_file: text_file.write("Purchase Amount: {}".format(TotalAmount))

If you are working with Python3.6 then you will have to use f-string which is introduced in Python3.6:-

with open("Output.txt", "w") as text_file:

print(f"Purchase Amount: {TotalAmount}", file=text_file)

To know more about this you can have a look at the following video tutorial:-

Learn more about Python from an expert. Enroll in our Python Course!

Related questions

0 votes
1 answer
asked Oct 15, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
0 votes
2 answers
asked Sep 12, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer

Browse Categories

...