Search code examples
pythonescaping

In Python, how do I have a single backslash element in a list?


To start, I'm running Python 3.6 on windows 10.

The backslash character in python is a special character that acts as an "escape" for strings. Because of this, it cannot be printed directly. If I want to print a single backslash, doing this will not work:

print("\") #error message

The way to get around this is to simply add another backslash, like so:

print("\\") #\

So far so good. However, when you make a list of string elements, like below:

list_of_strings = ['<','>','\u20AC','\u00A3','$','\u00A5','\u00A4','\\']
print(list_of_strings)

The following is printed out: ['<', '>', '€', '£', '$', '¥', '¤', '\\'] Which is not ideal. Trying to use just one backslash('\') in the string will result in the same EOL error as mentioned in the beginning. If you try to directly print out the backslash using a single instance of its unicode (u005C), like so:

print(['<','>','\u20AC','\u00A3','$','\u00A5','\u00A4','\u005C'])

The output still has a double slash: ['<', '>', '€', '£', '$', '¥', '¤', '\\']

One other thing I tried was this:

bs = "\\"
print(bs) #prints a single \
list_of_strings = ['a','b','c','d',bs]
print(list_of_strings) #prints ['a', 'b', 'c', 'd', '\\']

So is there a way for me to be able to set this up so that a single backslash will be printed out as a string element in a list?

I appreciate any help you can give me!


Solution

  • When printing a list in python the repr() method is called in the background. This means that print(list_of_strings) is essentially the same thing (besides the newlines) as:

    >>> for element in list_of_strings:
    ...     print(element.__repr__())
    ... 
    '<'
    '>'
    '€'
    '£'
    '$'
    '¥'
    '¤'
    '\\'
    

    In actuality the string stored is '\' it's just represented as '\\'

    >>> for element in list_of_strings:
    ...     print(element)
    ... 
    <
    >
    €
    £
    $
    ¥
    ¤
    \
    

    If you print out every element individually as above it will show you the literal value as opposed to the represented value.