4

I have strings with control-characters in them, and I want to make them visible (for printing documentation of them, for instance).

For example, I have

dialect = csv.sniffer().sniff(csvfile.read(1024))

and I want to print the contents of

dialect.lineterminator

This obviously contains control-character(s). They don't become printable by sticking a "\" in front of them. I'd like to see \n \r or both, as appropriate.

As I'm using Python 3, similar questions have proposed using str.encode, such as

    dialect.lineterminator.encode('unicode-escape')

but if I print this, I get

    b'\\r\\n'

which is, in spite of its appearance, just two bytes. I want a unicode string such as

    "\\r\\n"

which is a 4-character string. I'm not after the unicode encoding, but the escape sequence.

4dummies
  • 759
  • 2
  • 9
  • 22
  • It turns out the answer is more simple than I thought possible. The result I want is exactly `repr(dialect.lineterminator)` or possibly `repr(dialect.lineterminator)[1:-1]` – 4dummies Dec 13 '16 at 01:04

1 Answers1

9

You can just convert the string to a raw string:

>>> a = 'foo\nbar'
>>> print a
foo
bar
>>> print a.encode('string-escape')
foo\nbar

Note: this is for Python2 only, in 3 the equivalent is str.encode('unicode_escape') AFAIK

Here's a similar question I recently asked.

Community
  • 1
  • 1
Will
  • 4,299
  • 5
  • 32
  • 50