[Python-ideas] str.startswith taking any iterator instead of just tuple

Andrew Barnert abarnert at yahoo.com
Sun Jan 5 18:48:31 CET 2014


On Jan 5, 2014, at 3:09, David Townshend <aquavitae69 at gmail.com> wrote:

> Reading this thread made me start to think about why a string is a sequence, and I can't actually see any obvious reason, other than historical ones.

You've seriously never indexed or sliced a string? Those are the two core operations in sequences, and they're obviously useful on strings.

> Every use case I can think of for iterating over a string either involves first splitting the string, or would be better done with a regex

People have mentioned use cases for iterating strings in this thread. And it's easy to think of more. There are all kinds of algorithms that treat strings as sequences of characters. Sure, many of these functions are already methods on str or otherwise built into the stdlib, but that just means they're implemented by iterating the string storage in C with a loop around "*++s". And if you want to extend that set of builtins with similar functions, how else would you do it but with a "for ch in s" loop? (Well, you could "for ch in list(s)", but that's still treating strings as iterables.) For example, many people are asked to write a rot13 function in one of their first classes. How would you write that if strings weren't iterables? There's no way a regex is going to help you here, unless you wanted to do something like using re.sub('.') as a convoluted and slow way of writing map.


More information about the Python-ideas mailing list