A string without quotes in a string (python)

I am trying to write text to a file, but I have other text that I need to include, in addition to the target line. When I iterate over entire lines, it is printed with quotation marks, since quotation marks are needed for other text. How to remove quotes from a string that I insert every loop in?

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)

Conclusion: You need to have material before the "random" and after each line of the loop; Required Conclusion: You need to have material before random and after each line of the loop

+4
source share
2 answers

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 %swith operator %:

>>> for item in li:
...    print("before %s after" % item)
... 
before random after
before stuff after
before 1 after

( list, Python ...)

+3

, , %s, %a, (IE %s - ).

megaing

+1

Source: https://habr.com/ru/post/1693119/


All Articles