PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, September 15, 2022

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

 September 15, 2022     backslash, escaping, printing, python     No comments   

Issue

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


Solution

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


Answered By - kindall
Answer Checked By - Terry (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing