[Tutor] Question about strings

Alan Gauld alan.gauld at btinternet.com
Mon Aug 9 19:32:31 CEST 2010


"Daniel" <asmosis.asterix at gmail.com> wrote

> *1)s = 'colorless'
> 2)ss = s[:4] + 'u' + s[4:]
>
> *I do not understand something. So on the second line, the slicing
> lasts from the start of the s string to the forth character.

Correct, slices include the first index but not the last.

> does the counting start? 0 or 1?

It starts with 0.  [:4] means 0,1,2,3

> From this code it's obvious that it starts from one,
> but how, strings counting doesn't start from 0?

No, it starts from 0.

> len(s) i get 9 but if I do s[9] I get an error,
> out of range.

Yes but if you do

range(0,len(s))
you get the right set of values to index s. - 0...(9-1)
A slice works like range()

> please someone clear me this indexing thing? It's so frustrating and
> confusing.

It is confusing until you get used to it. You will find over time that
it is actually more convenient that way, but it is very strange for 
newbies.
There are some languages that start indexing at 1 but they get into
all sorts of complications in other areas, most language designers
have settled for zero based indexes as the best overall solution.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/




More information about the Tutor mailing list