Justlest
Justlest

Reputation: 53

String without quotes within a string?

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

Answers (2)

dawg
dawg

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

Xantium
Xantium

Reputation: 11603

Your code is right except that when you need to use %s rather than %a because you want to input as a string (IE %s is a string).

As indicated by in the comments by megaing

Upvotes: 1

Related Questions