I am having problem in printing something specific. I am trying to write some parameters and text into a file using the function f.write() . My problem is the one below:
Let’s say that I want to print inside the file the specific text:
Hello, my name is “Dionisis” and I am “30” years old.
If I type f.write(“Hello, my name is “Dionisis” and I am “30” years old”) it just separates the whole function inside.So, how to print inside a text with " " shown in the file?
Thank you in advance.
You can use single quotes:
f.write('Hello, my name is "Dionisis" and I am "30" years old')
Python allows you to use either single or double quotes to delimit a
string. These are both the same:
The reason for this is so that you can use the other sort of quote
inside a string. If you try this:
"Hello my name is "Dionisis" and I ..."
Python reads it as a string, then the word Dionisis, then another
"Hello my name is "
" and I ..."
which is not legal syntax and will cause an error. So you either use
backslashes to escape the quotes:
"Hello my name is \"Dionisis\" and I ..."
but that is annoying. So we can flip the quotes to single quotes
'Hello my name is "Dionisis" and I ...'
There is nothing special about single quotes as delimiters and double
quotes inside the string. You can do it the other way:
"Hello, I'm Dionisis. What's your name?"
Thank you so much for your help. I really appreciate your willingness to help and the time you spent to answer. Thank you. It was a very helpful answer.