In other words, how do I know which one to use?
I know when I use strings. I would do
string = "This is a string"
When would I use ' ' or """ """?
Generally, double quotes are used for string representation and single quotes are used for regular expressions, dict keys or SQL. Hence both single quote and double quotes depict string in python but it's sometimes our need to use one type over the other.
Note: Triple quotes, according to official Python documentation are docstrings, or multi-line docstrings and are not considered comments. Anything inside triple quotes is read by the interpreter. When the interpreter encounters the hash symbol, it ignores everything after that. That is what a comment is defined to be.
Using single and double quotes are equivalent. The only difference is when we use an apostrophe or additional quotation marks inside the string, in which case we may need to escape those punctuation(s) using a backslash ( \ ).
'...'
and "..."
are equivalent. If you have an apostrophe in the string, it is easier to use "..."
so you don't have to escape the apostrophe. If you have quotes in the string, it's easier to use '...'
so you don't have to escape the quotes.
Triple quotes (both varieties, """
and '''
are permitted) allow the string to contain line breaks. These are commonly used for docstrings (and other multi-line comments, including "commenting out" code) and for embedded snippets of other computer languages such as HTML and SQL.
https://docs.python.org/2.0/ref/strings.html
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