What is ''r'' in python?

Gary Herron gherron at islandtraining.com
Wed Jan 7 01:47:44 EST 2009


Harish Vishwanath wrote:
> Hello,
>
> I accidentally did this in the shell.
>
> >>> ''r''
> ''
> >>> ''r'' == ''
> True
> >>> ''r'' == ""
> True
>
> That is <singlequote singlequote r singlequote singlequote>. However
> if I try ->
>
> >>> ''c''
>   File "<stdin>", line 1
>     ''c''
>       ^
> SyntaxError: invalid syntax
> >>> ''z''
>   File "<stdin>", line 1
>     ''z''
>       ^
> SyntaxError: invalid syntax
>
> Any other character that way is Invalid Syntax. What is so special
> about character r enclose within a pair of single quotes?

Well...  For starters, that's not what you have.  Python does not have
"pairs of single quotes", so you'll have to look elsewhere for an
answer.  Here it is, but bear with me for a minute:

Strings can be created in many different ways:
  'a'          # single quotes
  "b"        # double quotes
  '''c'''       # Triple single quotes
  """c"""   # Triple double quotes
Then there are the so-called raw strings which interpret backslashes
differently
  r'a'
  r"b"
  ...
Then there are also Unicode strings -- but we don't need those here.

So what you have when you type
  ''r''    # (That's four single quotes although your font may make it
look like two double quotes.)
is an empty string
  ''
followed by another empty string (using raw syntax)
  r''

The last piece of the puzzle is a (seemingly) little know feature of
Python's syntax:  If you specify two strings (in any syntax) without an
operator between them, they are automatically concatenated.  Like this:

>>> 'a'   'b'
'ab'
>>> "a"  'b'
'ab'
>>> 'a'   r'b'
'ab'
>>> 'a' u'b'
u'ab'


So there you have it.  Your mystery is the (automatic) concatenation of
two empty strings.


Gary Herron






>
> Regards,
> Harish
> ------------------------------------------------------------------------
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>   




More information about the Python-list mailing list