In my compiler class, I decided to write my compiler in Python, since I like programming in Python, although I encounter an interesting problem with the way characters are printed. The lexer I'm writing requires that strings containing form and backspace characters be printed on stdout in a very specific way: enclosed in double quotes and printed as \ f and \ b, respectively. The closest I got:
print("{0!r}".format("\b\f"))
what gives
'\x08\x0c'
Pay attention to single quotes and utf8 coding. The same team with two other characters that I deal with almost works:
print("{0!r}".format("\n\t"))
gives:
'\n\t'
To be clear, a result (including quotation marks) that must conform to the specification,
"\b\f"
, \b \f "\ b" "\ f" , , ... "\" - , Python , , , "\ b\f", .
, , . , . , , , .
EDIT: . , , . , , , "\n" , "\ t". , raw, "\ b" "\ f" , .
, , , , , , , "\n", "\ t", "\ b" , "\ f" escape-, . string.Formatter.
EDIT2: , , - . - :
print('"{0!s}"'.format(a.replace("\b", "\\b").replace("\t", "\\t").replace("\f", "\\f").replace("\n","\\n")))