strtr? (was startsin ?

I think `strtr`_ in php is also very useful when escaping something. _ strtr: http://jp.php.net/manual/en/function.strtr.php For example: .. code-block:: php php> = strtr("foo\\\"bar\\'baz\\\\", array("\\\\"=>"\\", '\\"'=>'"', "\\'"=>"'")); "foo\"bar'baz\\" .. code-block:: python In [1]: "foo\\\"bar\\'baz\\\\".replace('\\"', '"').replace("\\'", "'").replace('\\\\', '\\') Out[1]: 'foo"bar\'baz\\' In Python, lookup of 'replace' method occurs many times and temporary strings is created many times too. It makes Python slower than php. And replacing order may cause very common mistake. .. code-block:: python In [4]: "foo\\\"bar\\'baz\\\\'".replace('\\\\', '\\').replace('\\"', '"').replace("\\'", "'") Out[4]: 'foo"bar\'baz\'' When I wrote HandlerSocket_ client in pure Python. I use dirty hack for speed. http://bazaar.launchpad.net/~songofacandy/+junk/pyhandlersocket/view/head:/h... I believe Pythonic means simple and efficient. My code is not Pythonic at all. .. _HandlerSocket: https://github.com/ahiguti/HandlerSocket-Plugin-for-MySQL On Sat, Oct 1, 2011 at 12:30 AM, Tarek Ziadé <ziade.tarek@gmail.com> wrote:
-- INADA Naoki <songofacandy@gmail.com>

INADA Naoki dixit (2011-10-01, 01:18):
For this particular case I'd use .decode('string_escape') for Py2.x str and .decode('unicode_escape') for Py2.x unicode strings. And in Py3.x I'd use... Er... In Py3.x the planned mechanism of str.transform()/untransform() (here: untransform('unicode_escape')) would be ideal -- but it has not been re-introduced yet: http://bugs.python.org/issue7475 -- and IMHO it should be as a clear way to do such transformations. Cheers. *j

INADA Naoki dixit (2011-10-01, 01:18):
For this particular case I'd use .decode('string_escape') for Py2.x str and .decode('unicode_escape') for Py2.x unicode strings. And in Py3.x I'd use... Er... In Py3.x the planned mechanism of str.transform()/untransform() (here: untransform('unicode_escape')) would be ideal -- but it has not been re-introduced yet: http://bugs.python.org/issue7475 -- and IMHO it should be as a clear way to do such transformations. Cheers. *j
participants (3)
-
INADA Naoki
-
Jan Kaliszewski
-
Masklinn