4

I just ran into what seemed to me to be bizarre string formatting behavior in python. It turned out to be caused by carriage return characters ('\r') I didn't know were there. Here's an example:

>>> text = 'hello\r' >>> '(SUBJECT "%s")' % (text) '(SUBJECT "hello\r")' >>> print '(SUBJECT "%s")' % (text) ")UBJECT "hello 

I tried the same thing in C (on a couple machines) as a sanity check.

#include <stdio.h> int main() { char *text = "hello\r"; printf("(SUBJECT \"%s\")\n", text); return 0; } 

Output:

% ./a.out ")UBJECT "hello 

Is this desired behavior? If so, can someone explain what is going on?

2
  • "carriage return" is a quaint old fashioned term meaning "go to beginning of line". Commented Jul 13, 2013 at 22:01
  • Use "./a.out | od -c" to see what really came out. Commented Sep 6, 2013 at 18:36

1 Answer 1

8

It (\r) is a carridge return without a linefeed so the cursor moves back to the start of the current line without moving onto a new line and therefore overwriting what is already displayed.

The behaviour depends on your console and whether it interprets CR and LF as individual operations.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.