I'm attempting to join a tuple of two strings using the .join method as follows.

>>> my_tuple = ("parent", "child")
>>> "\\".join(my_tuple)

I would expect this to return parent\child, however, it returns parent\\child.

Why is this? Escaping the backslash with another backslash works fine if I attempt to simply print it.

>>> print "parent\\child"
>>> parent\child

Observed in Python 2.7.3 on Windows 7.

有帮助吗?

解决方案

You got that right, it's only printing a double backslash because you are not printing it:

>>> '\\'.join(my_tuple)
'parent\\child'
>>> print '\\'.join(my_tuple)
parent\child

it's the same difference than __str__ and __repr__:

>>> '\\'.__repr__()
"'\\\\'"
>>> '\\'.__str__()
'\\'
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top