Solo98
Solo98

Reputation: 21

How to write variables in between single quotes in a textfile in python?

I have a bunch of strings to write in a text file. I want the strings to be written in simple quotes in the file, so I tried using this code: file.write("the variable is = \"" + my_string + "\" ") I wanted the output in the txt file to be: the variable is = 'my_string' but instead I get the variable is = "my_string" in double quotes.

What should I do to get the right output?

Upvotes: 0

Views: 1299

Answers (3)

Solo98
Solo98

Reputation: 21

Thanks to you all for your advice !! It worked well with the solution proposed by Deepak Tripathi, which is file.write(f"the variable is = '{variable_name}' ") ! Thanks, thats exactly what i nedeed :)

Upvotes: 1

cao-nv
cao-nv

Reputation: 384

Using single quotes inside a string marked by a double quote pair will make the single quote as normal character.

with open("text.txt", "w") as fp:
    fp.write("the variable is = 'my string'")

enter image description here

Upvotes: 0

earthdomain
earthdomain

Reputation: 68

Try the following and see if this works

file.write("the variable is = '" + my_string + "' ")

Upvotes: 0

Related Questions