2

I'm getting the strings passed in and want to print the buffer in raw format (printing the double backslash as is) How do I tell the string.format() this is a 'raw' string and don't use the backslash character?

>>> machines=['\\JIM-PC', '\\SUE-PC', '\\ANN-PC']
>>> for machine in machines:
...     print 'Machine Found %s' % (machine)
...
Machine Found \JIM-PC
Machine Found \SUE-PC
Machine Found \ANN-PC
Zero Piraeus
  • 56,143
  • 27
  • 150
  • 160
Craig
  • 173
  • 2
  • 3
  • 9

2 Answers2

3

The easiest way to do it would be to just double down on your slashes, since "\\" is considered a single slash character.

machines=['\\\\JIM-PC','\\\\SUE-PC','\\\\ANN-PC']
for machine in machines:
    print 'Machine Found %s' % (machine)

You could also use the method str.encode('string-escape'):

machines=['\\JIM-PC','\\SUE-PC','\\ANN-PC']
for machine in machines:
    print 'Machine Found %s' % (machine.encode('string-escape'))

Alternatively, you could assign the value as well, if you want the encoding to stick to the variables for later use.

machines=['\\JIM-PC','\\SUE-PC','\\ANN-PC']
for machine in machines:
    machine = machine.encode('string-escape')
    print 'Machine Found %s' % (machine)

I found the str.encode('string-escape') method here: casting raw strings python

Hope this helps.

Edit

Re Chris: print(repr(machine)) works too, as long as you don't mind that it includes the quote marks.

Community
  • 1
  • 1
Allan B
  • 329
  • 2
  • 9
0

The string literal '\\JIM-PC' does not contain a double backslash; what you see is the representation of a single backslash in a regular string literal.

This is easily shown by looking at the length of the string, or iterating over its individual characters:

>>> machine = '\\JIM-PC'
>>> len(machine)
7
>>> [c for c in machine]
['\\', 'J', 'I', 'M', '-', 'P', 'C']

To create a string containing a double backslash, you can either use a raw string literal: r'\\JIM-PC', or represent two backslashes appropriately in a regular string literal: '\\\\JIM-PC'.

Zero Piraeus
  • 56,143
  • 27
  • 150
  • 160