我刚刚在Python中遇到了一些看起来很奇怪的字符串格式化行为。结果发现是由于我不知道存在的回车符('\r')所引起的。以下是一个示例:
>>> text = 'hello\r'
>>> '(SUBJECT "%s")' % (text)
'(SUBJECT "hello\r")'
>>> print '(SUBJECT "%s")' % (text)
")UBJECT "hello
为了核实,我在几台机器上试过用C语言做同样的事情。
#include <stdio.h>
int main()
{
char *text = "hello\r";
printf("(SUBJECT \"%s\")\n", text);
return 0;
}
输出:
% ./a.out
")UBJECT "hello
这是期望的行为吗?如果是,有人能解释一下发生了什么吗?