Craig
Craig

Reputation: 183

Print strings with backslashes in Python 2.7

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

Upvotes: 2

Views: 2881

Answers (2)

schesis
schesis

Reputation: 59118

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'.

Upvotes: 0

Allan B
Allan B

Reputation: 347

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.

Upvotes: 3

Related Questions