I knew that I could get unicode characters using the escape sequence, like this:
>>> print "\3"
♥
and I just wanted to look through available ASCII characters and written this:
for i in xrange(1, 99):
print "\%o" % i
and it prints “\1”, “\2”, “\3”, etc., so not unicode characters. I then tried it using %s, %r, and %d and none of those seem to work either.
It was much more interesting than seeing available ASCII characters so I started reading about string formating and ended up with this piece working:
for i in xrange(1, 99):
print "{:c}".format(i)
The question is – why the initial code wasn’t working?
Escape sequences in string literals are processed at “parse time”, not at “run time”.
If you write
Python parser sees a backslash followed by a percent sign and because this is not a valid escape sequence it will just keep both characters and then will also add
oas a normal character (note that in this Python is different from e.g. the C++ programming language that it would have interpreted that string just as"%o"because in that language a backslash before a percent sign is interpreted as a percent sign only).At run time the formatting operator will see as left side a string composed by three characters, a backslash and a
%osequence and that is the part that will be replaced by the right-hand side giving for example the string"\\1"for the input value 1 and that string is displayed as\1.