Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected format string behavior

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?

like image 295
Peter Enns Avatar asked Oct 25 '25 15:10

Peter Enns


1 Answers

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.

like image 180
tinman Avatar answered Oct 27 '25 05:10

tinman