Ziu
Ziu

Reputation: 659

Behavior of python's repr method

I understand that the goal of repr is to be unambiguous, but the behavior of repr really confused me.

repr('"1"')
Out[84]: '\'"1"\''
repr("'1'")
Out[85]: '"\'1\'"'

Based on the above code, I think repr just put '' around the string. But when i try this:

repr('1')
Out[82]: "'1'"
repr("1")
Out[83]: "'1'"

repr put "" around strings and repr("1") and repr('1') is the same.

Why?

Upvotes: 0

Views: 185

Answers (3)

Seer.The
Seer.The

Reputation: 487

From documentation:

repr(object): Return a string containing a printable representation of an object.

So it returns a string that given to Python can be used to recreate that object.

Your first example:

repr('"1"')    # string <"1"> passed as an argument
Out[84]: '\'"1"\''    # to create your string you need to type like '"1"'.
# Outer quotes are just interpretator formatting

Your second example:

repr("'1'")    # you pass a string <'1'>
Out[85]: '"\'1\'"'    # to recreate it you have to type "'1'" or '\'1\'',
# depending on types of quotes you use (<'> and <"> are the same in python

Last,

repr('1')    # you pass <1> as a string
Out[82]: "'1'"    # to make that string in python you type '1', right?
repr("1")    # you pass the same <1> as string
Out[83]: "'1'"    # to recreate it you can type either '1' or "1", does not matter. Hence the output.

I both interpreter and repr set surrounding quotes to ' or " depending on content to minimize escaping, so that's why output differs.

Upvotes: 1

Anonymous
Anonymous

Reputation: 12080

The python REPL (and Ipython in your case) print out the repr() of the output value, so your input is getting repred twice.

To avoid this, print it out instead.

>>> repr('1') # what you're doing
"'1'"
>>> print(repr('1')) # if you print it out
'1'
>>> print(repr(repr('1'))) # what really happens in the first line
"'1'"

The original (outer) quotes may not be preserved since the object being repred has no idea what they originally were.

Upvotes: 1

Thomas
Thomas

Reputation: 181715

There are three levels of quotes going on here!

  1. The quotes inside the string you're passing (only present in your first example).

  2. The quotes in the string produced by repr. Keep in mind that repr tries to return a string representation that would work as Python code, so if you pass it a string, it will add quotes around the string.

  3. The quotes added by your Python interpreter upon printing the output. These are probably what confuses you. Probably your interpreter is calling repr again, in order to give you an idea of the type of object being returned. Otherwise, the string 1 and the number 1 would look identical.

    To get rid of this extra level of quoting, so you can see the exact string produced by repr, use print(repr(...)) instead.

Upvotes: 1

Related Questions