Reputation: 53
I'm trying to write text to file, but I have other text I need to include besides the targeted string. When I'm looping over the targeted strings it is printed with quotes as the quotes are needed for other text. How to remove quotes from a string that I'm inserting each loop?
list=['random', 'stuff', 1]
with open(textfile, 'a') as txtfile:
for item in list:
print("""Need to have stuff before %a and after each loop string"""
%item, file=txtfile)
Output: Need to have stuff before 'random' and after each loop string.
Desired output: Need to have stuff before random and after each loop string.
Upvotes: 5
Views: 3451
Reputation: 104032
You can use str.format:
>>> li=['random', 'stuff', 1]
>>> for item in li:
... print("before {} after".format(item))
...
before random after
before stuff after
before 1 after
Or you can use %s
with the %
operator:
>>> for item in li:
... print("before %s after" % item)
...
before random after
before stuff after
before 1 after
(And don't call a list list
or you will overwrite the Python function of the same name...)
Upvotes: 3