0

I want to maintain a variable with a string which contains backslashes and don't want to alter that. When I try to use the string, it gets extra backslashes as escape characters. I tried with 'r' ( raw ) modifier - but it didn't help.

Python 2.7.3 (default, Feb 27 2014, 19:58:35)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> s = r'\abc'
>>> s
'\\abc'

I have a test where I am trying to have an array of possible values with ''. But when I take them out, it doesn't come as expected:

>>> value =  [r'"\1"', r'"\\1"', r'"\\\1"' ]
>>> for val in value:
...   print value
...
['"\\1"', '"\\\\1"', '"\\\\\\1"']
['"\\1"', '"\\\\1"', '"\\\\\\1"']
['"\\1"', '"\\\\1"', '"\\\\\\1"']

How do I do this?


I saw questions regarding the problem with backslash related issues in Python. But I couldn't get a specific answer for the problem that I am hitting.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
user2677279
  • 127
  • 3
  • 10

3 Answers3

0

Your string is not altered. Use the print statement to print the actual variable contents.

In the second example, you just print the whole list, not the items present inside the list.

>>> s = r'\abc'
>>> print s
\abc
>>> value =  [r'"\1"', r'"\\1"', r'"\\\1"' ]
>>> for val in value:
        print val


"\1"
"\\1"
"\\\1"
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
0

You are printing the representation of the strings as if they were normal strings, which they are not.

When you use raw string literals, then print the string. Any escape character like \ is itself escaped in the representation, leading to a multiplication of \ symbols. Your strings are fine.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
MattDMo
  • 100,794
  • 21
  • 241
  • 231
  • @Joel, I'm not sure if you're able to yet, but higher-rep users can click on the score of a question or answer and see the number of votes in each direction. Both of the answers to this question got **2** downvotes within a minute or two of being posted. Somebody and their sock puppet was not feeling charitable... – MattDMo Feb 17 '15 at 05:07
0

IDK if this helps your specific problem, but if r\ isn't working, you can always put two backslashes to force python to interpret it literally. Instead of "r\abc", use "\abc". I had to do this for one of my class tests as well, and it helped me a lot to use \ because it works reliably, whereas r\ has some parameters to keep in mind.