'How to use a string with backslashes in Python

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.



Solution 1:[1]

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"

Solution 2:[2]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Peter Mortensen
Solution 2 Peter Mortensen