Is there any reason to use double or single quotes?


#1

Question

If both are valid, why would you use double or single quotes for any given string?

Answer

It depends on the string you’re writing or storing for sure. The important thing is to always have the same type of quote on the outside, and always have a closing outside quote for an opening outside quote.
If we need to write a string with an apostrophe in the middle, it’s best to use double quotes on the outside, otherwise it’ll think we have an extra quote!

print “This looks right, doesn’t it?”

print ‘This doesn’t look right, does it?’

See how the second example looks like we closed off our string after the ‘n’ in “doesn’t”?
Another common practice is using double quotes for strings and single quotes for single characters, like ‘n’.


FAQ: Learn Python - Python Syntax - Strings
#2

I still don’t understand why you would use double quotes. It seems pointless to me to have a double quote.


#3

Why does it seem pointless?

if i had to choice between:

'This doesn\'t look right, does it?'

and:

"This doesn't look right, does it?"

i would pick the latter, so i don’t have to escape the ' used in the string.


#4

there is no difference between the two choices


#5

one just “looks better” and the double quotes and single quotes don’t change anything


#6

if you want to use single or double quotes within the string, then user the other to enclose the string is a lot easier.


#7

There really is no set rule or reason to use one or the other. Personal preference will prevail. Needless, production environments in collaborative projects will prevail even further in what they dictate as best practice, style guidelines, etc.

Eg.

Generating HTML

$div = '<div class="item">' + item + '</div>'

The HTML on inspection has a double quoted attribute which is typical in HTML composition. I am actually a stickler about this one style guide recommendation. I love to see HTML attributes in double quotes when inspecting., The E. B. White approach.


#8

In the next step we have to debug and when i add " to the string it comes twice like this “” and the comand executes an error what should i do to us only one on both of sides.
i tried but on the left side of the string it comes once while on ending it comes twice.
any solution???


#9

just type "" first, then insert the string inside.


#10

Thanx for this answer.I also run this type of problem.
print"This looks, right doesn’t it?"-it easily run,
but,
print’This looks, right doesn’t it?’-it has problem of this type
(File “script.py”, line 7
print’This looks, right doesn’t it?’
^
SyntaxError: invalid syntax)


#11

When outer quotes (string delimiters) match any that are within the text, a conflict results. The solution in this case is escapement

'This looks, right doesn\'t it?'

Using an escape tells the interpreter that what follows is a printable character.


#13