What does '\r' mean? What does it do? I have never seen it before and its giving me headaches. It doesnt seem to have any purpose, since 'a\ra' prints as 'aa', but its not the same as the string 'aa'. Im using python 2.6
It's an old control character from typewriters. It means "carriage return". In this time, when you pressed "enter", you were going to the next line, then the carriage went back to the beginning of the line (hence the carriage return). Then with computers, different OSes made different choices to represent new lines. On windows, you have "\r\n" (carriage return + new line). On unices, you have "\n" only (no need to do a carriage return, it was sort of implied by the new line). On old mac OS, you had "\r" only.
Nowadays, it's not used except for newlines (or I don't know other usages).
It's the escape for Carriage Return. On my console, running on Windows, print 'a\ra'
results in ...
a
a
... getting printed to stdout.
Here's a list of all valid escapes.
\newline
- Ignored\\
- Backslash ()\'
- Single quote (')\"
- Double quote (")\a
- ASCII Bell (BEL)\b
- ASCII Backspace (BS)\f
- ASCII Formfeed (FF)\n
- ASCII Linefeed (LF)\N{name}
- Character named name in the Unicode database (Unicode only)\r
- ASCII Carriage Return (CR)\t
- ASCII Horizontal Tab (TAB)\uxxxx
- Character with 16-bit hex value xxxx (Unicode only)\Uxxxxxxxx
- Character with 32-bit hex value xxxxxxxx (Unicode only)\v
- ASCII Vertical Tab (VT)\ooo
- Character with octal value ooo\xhh
- Character with hex value hh
should be a Carriage Return...something like a new line... look http://www.wilsonmar.com/1eschars.htm
For me (on a Mac OS X 10.5 Terminal.App, Python 2.6.5):
>>> print 'a\ra'
a
or to give a better example:
>>> print 'longstring\rshort'
shorttring
IOW, the \r
"returns the cursor to the start of the line" (without initiating a new long) so that 'short'
"overwrites" the beginning of 'longstring'
.
This effect is nice to show to the user a single-line "current status" being update during a long operation -- use print '\rupdate',
with a trailing comma to avoid emitting a new-line character, to update the status by overwriting the previous one. Of course you need to ensure each updated string thus shown is at least as long as the previous one (easy by just padding with spaces).
Do note that other responders have noticed different visual effects on their platforms (you yourself have seen \r
disappear without effect, which is unprecedented in my experience) so this nice way to provide updates won't work well on every platform!-)