The inverse of .join
Steven D'Aprano
steve at REMOVE-THIS-cybersource.com.au
Thu Jun 17 23:01:19 EDT 2010
On Thu, 17 Jun 2010 17:45:41 +0000, Neil Cerutti wrote:
> What's the best way to do the inverse operation of the .join function?
str.join is a many-to-one function, and so it doesn't have an inverse.
You can't always get the input back unchanged:
>>> L = ["a", "b", "c|d", "e"]
>>> s = '|'.join(L)
>>> s
'a|b|c|d|e'
>>> s.split('|')
['a', 'b', 'c', 'd', 'e']
There's no general way of getting around this -- if split() takes input
"a|b|c", there is no way even in principle for it to know which of these
operations it should reverse:
"|".join(["a", "b", "c"])
"|".join(["a|b", "c"])
"|".join(["a", "b|c"])
"|".join(["a|b|c"])
"b".join(["a|", "|c"])
The behaviour with the empty string is just a special case of this.
--
Steven
More information about the Python-list
mailing list