Home > Software design >  Python: single backslash automatically replaced by double backslash when printing a list
Python: single backslash automatically replaced by double backslash when printing a list

Time:04-23

I have an array/list of strings that contain a single backslash.

stringArray = ['this \\ is', 'a \\ sample', 'backslash \\ text']

When I print them in the console separately they are displayed exactly as they are intended to (considering that to write a single backslash you need to type two backslashes):

print(stringArray[0])
print(stringArray[2])

Outputs:

this \ is
backslash \ text

But whenever I print one or more elements of the array, the double backslash comes in:

print(stringArray)

Outputs:

['this \\ is', 'a \\ sample', 'backslash \\ text']

I have tried several methods to generate arrays and they always have the same result. Even by writing one single backslash in the strings the result is exactly the same. Why could this be happening and how can I get a list of strings with single backslashes?

CodePudding user response:

There is between directly printing a string and displaying a representation of that string.

A simple example of this is:

>>> '\\'
'\\'
>>> print('\\')
\

As you can one has quotes and two backslashes (which represents one backslash). When you print a list you are displaying a representation of all the strings contained.

How does this work?

When you call print() python firstly tries to call the __str__ method on the object if that doesn't exist it calls __repr__ for a 'debug' representation. Here's some more explanation but in short __str__ is to be readable and __repr__ is to unambiguously represent the object.

CodePudding user response:

As mentioned in this answer, calling __str__() on a list (which is what print() does), calls __repr__() on the items inside it. That is why you are getting 'this \\ is' instead of this \ is.

The solution is to use join() and construct the string yourself like so:

print(f'[{", ".join(stringArray)}]')

This results in the output:

[this \ is, a \ sample, backslash \ text]
  • Related