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.
The backslash character allows us to escape the single quote, so it's interpreted as the literal single quote character, and not as an end of string character. You can use the same approach to escape a double quote in a string. Copied! We use the backslash \ character to escape each double quote in the string.
To print a string list without quotes, use the expression '[' + ', '. join(lst) + ']' to create a single string representation of the list without the quotes around the individual strings.
Sometimes you might want to place quotation marks (" ") in a string of text. For example: She said, "You deserve a treat!" As an alternative, you can also use the Quote field as a constant.
Single and Double Quotes in JavaScript StringsStrings in JavaScript are contained within a pair of either single quotation marks '' or double quotation marks "". Both quotes represent Strings but be sure to choose one and STICK WITH IT. If you start with a single quote, you need to end with a single quote.
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...)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With