0

I thought I understood backslash escaping, but I don't get this behaviour:

foo = '\t'

gives the same string (i.e. \t) when I type foo in the Python interpreter, whereas

bar = '\i'

gives \\i. What's happening? I want to have just \i, because I'm writing it to a .tex file that I'm then compiling, and this seems to mess up the LaTeX commands.

Edit: it was in fact not this that was messing up my latex, as the answers below show

funklute
  • 581
  • 4
  • 21
  • 1
    Gives? Do you print? How? –  Feb 12 '15 at 07:58
  • good point, I mean when I type the variable in the interpreter (so I guess that calls print on it) – funklute Feb 12 '15 at 08:00
  • 3
    @funklute It's not exactly "printing". `print` gives a `__str__` representation of the object, and directly typing the variable gives a `__repr__` one. – Igor Hatarist Feb 12 '15 at 08:01
  • 1
    When you type the variable in the interpreter, it doesn't use `print()`, it uses `repr()`. – Dietrich Epp Feb 12 '15 at 08:01
  • Cool, so does writing to a file object use print() or repr()? – funklute Feb 12 '15 at 08:06
  • 1
    @funklute `file_object.write()` expects a character buffer (a string), so you should put a string there. Let's say you want to save a list content, the one you get using `print [1, 2, 3]`. You can't do `file_object.write([1, 2, 3])` directly. Though, you _can_ do `write(str([1, 2, 3]))` – Igor Hatarist Feb 12 '15 at 08:20

1 Answers1

1

"\t" is a tab (one character), "\i" contains two characters, the first of which is escaped by __repr__.

In [51]: len("\t")
Out[51]: 1

In [52]: len("\i")
Out[52]: 2

Edit: If you write to a file, your output will be fine.

with open("o.tex", "w") as o:
    o.write(">>>\t|\i|\t<<<\n")

The content of o.tex will then be

>>>     |\i|    <<<

You can see the two tabs \t as whitespace while all other characters are as-is.

  • that makes sense. If writing to a file object, is the __repr__ used? or the __str__ representation (as mentioned in the comments on the actual question) – funklute Feb 12 '15 at 08:03