What is the meaning of %r?
Background:
In Python, there are two builtin functions for turning an object into a string: str
vs. repr
. str
is supposed to be a friendly, human readable string. repr
is supposed to include detailed information about an object's contents (sometimes, they'll return the same thing, such as for integers). By convention, if there's a Python expression that will eval to another object that's ==, repr
will return such an expression e.g.
If returning an expression doesn't make sense for an object,
>>> print repr('hi')
'hi' # notice the quotes here as opposed to...
>>> print str('hi')
hi
repr
should return a string that's surrounded by < and > symbols e.g. <blah>
.To answer your original question:
%s
<-> str
%r
<-> repr
In addition:
You can control the way an instance of your own classes convert to strings by implementing __str__
and __repr__
methods.
class Foo:
def __init__(self, foo):
self.foo = foo
def __eq__(self, other):
"""Implements ==."""
return self.foo == other.foo
def __repr__(self):
# if you eval the return value of this function,
# you'll get another Foo instance that's == to self
return "Foo(%r)" % self.foo
What does %% mean in R
The infix operator %>%
is not part of base R, but is in fact defined by the package magrittr
(CRAN) and is heavily used by dplyr
(CRAN).
It works like a pipe, hence the reference to Magritte's famous painting The Treachery of Images.
What the function does is to pass the left hand side of the operator to the first argument of the right hand side of the operator. In the following example, the data frame iris
gets passed to head()
:
library(magrittr)
iris %>% head()
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1 5.1 3.5 1.4 0.2 setosa
2 4.9 3.0 1.4 0.2 setosa
3 4.7 3.2 1.3 0.2 setosa
4 4.6 3.1 1.5 0.2 setosa
5 5.0 3.6 1.4 0.2 setosa
6 5.4 3.9 1.7 0.4 setosa
Thus, iris %>% head()
is equivalent to head(iris)
.Often, %>%
is called multiple times to "chain" functions together, which accomplishes the same result as nesting. For example in the chain below, iris
is passed to head()
, then the result of that is passed to summary()
.
iris %>% head() %>% summary()
Thus iris %>% head() %>% summary()
is equivalent to summary(head(iris))
. Some people prefer chaining to nesting because the functions applied can be read from left to right rather than from inside out. When to use %r instead of %s in Python?
The %s
specifier converts the object using str()
, and %r
converts it using repr()
.
For some objects such as integers, they yield the same result, but repr()
is special in that (for types where this is possible) it conventionally returns a result that is valid Python syntax, which could be used to unambiguously recreate the object it represents.
Here's an example, using a date:
>>> import datetime
>>> d = datetime.date.today()
>>> str(d)
'2011-05-14'
>>> repr(d)
'datetime.date(2011, 5, 14)'
Types for which repr()
doesn't produce Python syntax include those that point to external resources such as a file
, which you can't guarantee to recreate in a different context. What does preceding a string literal with r mean?
The r
means that the string is to be treated as a raw string, which means all escape codes will be ignored.
For an example:
'\n'
will be treated as a newline character, while r'\n'
will be treated as the characters \
followed by n
.
Source: Python string literalsWhen an
'r'
or'R'
prefix is present,
a character following a backslash is
included in the string without change,
and all backslashes are left in the
string. For example, the string
literalr"\n"
consists of two
characters: a backslash and a
lowercase'n'
. String quotes can be
escaped with a backslash, but the
backslash remains in the string; for
example,r"\""
is a valid string
literal consisting of two characters:
a backslash and a double quote;r"\"
is not a valid string literal (even a
raw string cannot end in an odd number
of backslashes). Specifically, a raw
string cannot end in a single
backslash (since the backslash would
escape the following quote character).
Note also that a single backslash
followed by a newline is interpreted
as those two characters as part of the
string, not as a line continuation.
What is the difference between \r and \n?
They're different characters. \r
is carriage return, and \n
is line feed.
On "old" printers, \r
sent the print head back to the start of the line, and \n
advanced the paper by one line. Both were therefore necessary to start printing on the next line.
Obviously that's somewhat irrelevant now, although depending on the console you may still be able to use \r
to move to the start of the line and overwrite the existing text.
More importantly, Unix tends to use \n
as a line separator; Windows tends to use \r\n
as a line separator and Macs (up to OS 9) used to use \r
as the line separator. (Mac OS X is Unix-y, so uses \n
instead; there may be some compatibility situations where \r
is used instead though.)
For more information, see the Wikipedia newline article.
EDIT: This is language-sensitive. In C# and Java, for example, \n
always means Unicode U+000A, which is defined as line feed. In C and C++ the water is somewhat muddier, as the meaning is platform-specific. See comments for details.
Python the Hard Way - exercise 6 - %r versus %s
They are called string formatting operations.
The difference between %s and %r is that %s uses the str
function and %r uses the repr
function. You can read about the differences between str
and repr
in this answer, but for built-in types, the biggest difference in practice is that repr
for strings includes quotes and all special characters are escaped.
Difference between \n and \r?
In terms of ascii code, it's 3 -- since they're 10 and 13 respectively;-).
But seriously, there are many:
- in Unix and all Unix-like systems,
\n
is the code for end-of-line,\r
means nothing special - as a consequence, in C and most languages that somehow copy it (even remotely),
\n
is the standard escape sequence for end of line (translated to/from OS-specific sequences as needed) - in old Mac systems (pre-OS X),
\r
was the code for end-of-line instead - in Windows (and many old OSs), the code for end of line is 2 characters,
\r\n
, in this order - as a (surprising;-) consequence (harking back to OSs much older than Windows),
\r\n
is the standard line-termination for text formats on the Internet - for electromechanical teletype-like "terminals",
\r
commands the carriage to go back leftwards until it hits the leftmost stop (a slow operation),\n
commands the roller to roll up one line (a much faster operation) -- that's the reason you always have\r
before\n
, so that the roller can move while the carriage is still going leftwards!-) Wikipedia has a more detailed explanation. - for character-mode terminals (typically emulating even-older printing ones as above), in raw mode,
\r
and\n
act similarly (except both in terms of the cursor, as there is no carriage or roller;-)
\n
(the underlying runtime will translate that if you're on a weird OS, e.g., Windows;-). The only reason to use \r
is if you're writing to a character terminal (or more likely a "console window" emulating it) and want the next line you write to overwrite the last one you just wrote (sometimes used for goofy "ascii animation" effects of e.g. progress bars) -- this is getting pretty obsolete in a world of GUIs, though;-). What is the meaning \r carriage return and \f form feed in Java?
You rarely use either of them (in isolation) in modern applications.
\r
(carriage return) is what it sounds like if you're familiar with old-fashioned manual typewriters: It moves the "carriage" (the roll the paper is fed through) back to the beginning of the line. On a terminal (or similar), it moves the output point back to the beginning of the line, without moving down a line (usually).
\f
is (as you said) a formfeed, it tells old-fashioned printers to start a new page. In computer documents, it's sometimes used to indicate a page break.
Rounding things out, there's also line feed (aka "newline"): \n
. This means "move down a line." In some terminals, it just moves down a line without doing a carriage return; on others, it does both.
\n
(LF, newline) is the standard text file line break on *nix and derived operating systems. \r\n
(CRLF) is the standard text file line break on DOS and Windows. Back in the day, \r
(on its own) was the standard line break in text files on the Mac, prior to Mac OS X (which is *nix-derived).
What does /r/ mean in this ajax url call?
It's just the first part of the URL: /r/something/
The value of the url property is just a string /r/
concatted with the contents of the action
variable.
So, if action
is, say, getData
, the full URL would be /r/getData
.
Related Topics
Python-Pandas: the Truth Value of a Series Is Ambiguous
Why Can't You Add Attributes to Object in Python
How to Make a Local Variable (Inside a Function) Global
Tuple Unpacking Order Changes Values Assigned
Python Running as Windows Service: Oserror: [Winerror 6] the Handle Is Invalid
Python Observer Pattern: Examples, Tips
Splitting List Based on Missing Numbers in a Sequence
Django Abstract Models Versus Regular Inheritance
Is There a Simple Process-Based Parallel Map for Python
In Tensorflow, Get the Names of All the Tensors in a Graph
Asyncio Cancellederror and Keyboardinterrupt
Serve Image Stored in SQLalchemy Largebinary Column