5

In Python, when I print a string with a backslash, it prints the backslash only once:

>>> print(r'C:\hi')
C:\hi
>>> print('C:\\hi')
C:\hi

But I noticed that when you print a tuple of strings with backslashes, it prints a double backslash:

>>> print((r'C:\hi', 'C:\\there'))
('C:\\hi', 'C:\\there')

Why does it behave differently when printing the tuple?

(Note, this happens in both Python 2 and 3, and in both Windows and Linux.)

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
twasbrillig
  • 17,084
  • 9
  • 43
  • 67
  • 6
    Because when you print the tuple it is showing you the string contained within and not actually PRINTING the string – sshashank124 Mar 25 '15 at 00:08
  • Related: [Why do backslashes appear twice?](https://stackoverflow.com/q/24085680/674039) – wim Oct 12 '18 at 14:43
  • Note that this will also occur with lists and dicts. – Karl Knechtel Aug 07 '22 at 03:46
  • I added to the title because while this is the best version of the question I can find (by far), it's much more often asked about lists, and is probably asked more about dicts than tuples. – Karl Knechtel Aug 07 '22 at 03:54

1 Answers1

7

When you print a tuple (or a list, or many other kinds of items), the representation (repr()) of the contained items is printed, rather than the string value. For simpler types, the representation is generally what you'd have to type into Python to obtain the value. This allows you to more easily distinguish the items in the container from the punctuation separating them, and also to discern their types. (Think: is (1, 2, 3) a tuple of three integers, or a tuple of a string "1, 2" and an integer 3—or some other combination of values?)

To see the repr() of any string:

print(repr(r'C:\hi'))

At the interactive Python prompt, just specifying any value (or variable, or expression) prints its repr().

To print the contents of tuples as regular strings, try something like:

items = (r'C:\hi', 'C:\\there')
print(*items, sep=", ")

str.join() is also useful, especially when you are not printing but instead building a string which you will later use for something else:

text = ", ".join(items)

However, the items must be strings already (join requires this). If they're not all strings, you can do:

text = ", ".join(map(str, items))
kindall
  • 178,883
  • 35
  • 278
  • 309