[Python-ideas] strings as iterables - from str.startswith taking any iterator instead of just tuple

Chris Angelico rosuav at gmail.com
Sat Jan 4 06:32:04 CET 2014


On Sat, Jan 4, 2014 at 3:23 PM, Alexander Heger <python at 2sn.net> wrote:
>> The other point that comes to mind is that iteration and indexing are
>> closely related. I think most people would agree that "abcde"[1]
>> should be 'b' (granted, there's room for debate as to whether that
>> should be a one-character string or an integer with the Unicode
>> codepoint, but either way); it's possible to iterate over anything by
>> indexing it with 0, then 1, then 2, etc, until it raises IndexError.
>> For a string to not be iterable, that identity would have to be
>> broken.
>
> OK, I admit that not being able to iterate over something that can be
> indexed may be confusing.  Though indexing of strings is somewhat special in
> many languages.

I don't know that it's particularly special. In some languages, a
string is simply an array of small integers (maybe bytes, maybe
Unicode codepoints), so when you index into one, you get the integers.
Python deems that the elements of a string are themselves strings,
which is somewhat special I suppose, but only because the
representation of a character is a short string. And of course, there
are languages that treat strings as simple atomic scalars, no
subscripting allowed at all - I don't think that's an advantage over
either of the above. :)

When you index a string, you get a character. Whatever the language
uses to represent a character, that's what you get. I don't think this
is particularly esoteric, but maybe that's just me.

ChrisA


More information about the Python-ideas mailing list