'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?
Solution 1:[1]
Try the following and see if this works
file.write("the variable is = '" + my_string + "' ")
Solution 2:[2]
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 :)
Solution 3:[3]
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'")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | earthdomain |
| Solution 2 | Solo98 |
| Solution 3 | cao-nv |

