Jaimin Nimavat
Jaimin Nimavat

Reputation: 91

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 %r 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.

Upvotes: 1

Views: 69

Answers (2)

ospahiu
ospahiu

Reputation: 3525

Notice this line -> do_not = "don't". There is a single quote in this string, that means that single quote has to be escaped; otherwise where would the interpreter know where a string began and ended? Python knows to use "" to represent this string literal.

If we remove the ', then we can expect a single quote surrounding the string:

do_not = "dont"

>>> I also said: 'Those who know binary and those who dont.'.

Single vs. double quotes in python.

Upvotes: 1

zondo
zondo

Reputation: 20336

%r is getting the repr version of the string:

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

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.

Upvotes: 1

Related Questions