Why does printing a tuple (list, dict, etc.) in Python double the backslashes?

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))

Leave a Comment