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 
1
  • Try print(repr(machine)) Commented Feb 17, 2017 at 15:05

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks allan, the ''.encode('string-escape') is what I was looking for
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'.

1 Comment

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.