Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String without quotes within a string?

Tags:

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.

like image 283
Justlest Avatar asked Feb 03 '18 18:02

Justlest


People also ask

How do you ignore quotes in a 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.

How do you print a string without quotations?

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.

Can you have a string with a quote inside it?

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.

Do strings need quotation marks?

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.


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 %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...)

like image 94
dawg Avatar answered Sep 22 '22 12:09

dawg


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

like image 24
Xantium Avatar answered Sep 19 '22 12:09

Xantium