Jaimin Nimavat Jaimin Nimavat - 7 months ago 19
Python Question

The difference between these 2 strings?

I have recently started to learn Python and I am hoping that you will be able to help me with a question that has been bothering me. I have been learning Python online with Learn Python The Hard Way. In Exercise 6, I came across a problem where I was using the

string formatting operation and it was resulting in two different strings. When I printed one string, I got the string with the single quotes (
' '
). With another I was getting double quotes (
" "

Here is the code:

x = "There are %d types of people." % 10
binary = "binary"
do_not = "don't"
y = "Those who know %s and those who %s." % (binary, do_not)

print "I said: %r." % x
print "I also said: %r." % y

The result from the first print statement:

I said: 'There are 10 types of people.'.

The result from the second print statement:

I also said: "Those who know binary and those who don't.".

I want to know why one of the statements had a result with the single quotes (
' '
) and another with (
" "
P.S. I am using Python 2.7.


%r is getting the repr version of the string:

>>> x = 'here'
>>> print repr(x)

You see, single quotes are what are normally used. In the case of y, however, you have a single quote (apostrophe) inside the string. Well, the repr of an object is often defined so that evaluating it as code is equal to the original object. If Python were to use single quotes, that would result in an error:

>>> x = 'those who don't'
  File "<stdin>", line 1
    x = 'those who don't'
SyntaxError: invalid syntax

so it uses double quotes instead.