[Python-ideas] strtr? (was startsin ?
INADA Naoki
songofacandy at gmail.com
Fri Sep 30 18:18:20 CEST 2011
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:/handlersocket/client.py
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 at gmail.com> wrote:
> Hey,
>
> not sure how people do this, or if I missed something obvious in the
> stdlib, but I often have this pattern:
>
> starts = ('a', 'b', 'c')
> somestring = 'acapulco'
>
> for start in starts:
> if somestring.startswith(start):
> print "yeah"
>
>
> So what about a startsin() method, that would iterate over a sequence:
>
> if somestring.startsin('a', 'b', 'c'):
> print "yeah"
>
> Implementing it in C should be faster as well
>
> same deal with .endswith I guess
>
> Cheers
> Tarek
>
> --
> Tarek Ziadé | http://ziade.org
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas
>
--
INADA Naoki <songofacandy at gmail.com>
More information about the Python-ideas
mailing list