A curious bit of code...

Chris Angelico rosuav at gmail.com
Thu Feb 13 15:29:40 EST 2014


On Fri, Feb 14, 2014 at 6:32 AM, Mark Lawrence <breamoreboy at yahoo.co.uk> wrote:
>> There will be an exception only if it is zero-length. But good
>> point! That's a pretty sneaky way to avoid checking for a
>> zero-length string. Is it a popular idiom?
>>
>
> I hope not.

The use of slicing rather than indexing to avoid problems when the
string's too short? I don't know about popular, but I've certainly
used it a good bit. For the specific case of string comparisons you
can use startswith/endswith, but slicing works with other types as
well.

Also worth noting:

Python 2.7.4 (default, Apr  6 2013, 19:54:46) [MSC v.1500 32 bit
(Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> s1,s2=b"asdf",u"asdf"
>>> s1[:1],s2[:1]
('a', u'a')
>>> s1[0],s2[0]
('a', u'a')

Python 3.4.0b2 (v3.4.0b2:ba32913eb13e, Jan  5 2014, 16:23:43) [MSC
v.1600 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> s1,s2=b"asdf",u"asdf"
>>> s1[:1],s2[:1]
(b'a', 'a')
>>> s1[0],s2[0]
(97, 'a')

When you slice, you get back the same type as you started with. (Also
true of lists, tuples, and probably everything else that can be
sliced.) When you index, you might not; strings are a special case
(since Python lacks a "character" type), and if your code has to run
on Py2 and Py3, byte strings stop being that special case in Py3. So
if you're working with a byte string, it might be worth slicing rather
than indexing. (Though you can still use startswith/endswith, if they
suit your purpose.)

ChrisA



More information about the Python-list mailing list