Newbie: Simple question about string slices

Steven Adams adams_s at lab.eng.usyd.edu.au
Fri Jun 9 10:05:48 EDT 2000


Hi,



Ray Smith <Ray.Smith at fujitsu.com.au> wrote in message
news:8hpsl6$mve at newshost.fujitsu.com.au...

> s = "abcdefg"
>
> I assumed s[2:2] to be equal to 'c',
> but when I tried it it equals '' (empty).
> The way I read this is give me the slice from index 2 to index 2.

as I see it, it does do this - I explain myself at the end :-)

> I also "feel like" s[:2] + s[2:] should be equal to 'abccdef'

its just how the slicing has been defined to work, probably a result of the
first index being zero - last index beind len()-1
(It's late and I'm tired from studying for exams :-|

> My question is:
> If given a slice s[a:b]
> can I assume index "b" means upto but not including the index "b"?
>
> eg.  s="abcdef"
>
> s[:3] = "abc", meaning from index 0, upto but not including index 3
> s[3:] = "def", meaning from index 3 to the end of the string
>

yes

> I guess another way to ask my question is:
> Why is s[a:a] always '' (empty) ?

because you are going 'from' the _start_ index 'a' to the _start_ of the
index 'a' - if that makes sense.
i.e. if you think of it in physical terms, the total displacement is zero if
I go from where I am, to where I am, I haven't gone anywhere.

> Hope someone out there in Python land can make sense of my question!

made sense of it, though I'm not sure if I made sense :-)

> Thanks
> Ray Smith

no probs,

Steven

DISCLAIMER: I'm not that experienced at Python programming, and it's late
(or as my watch tells me, its now early)





More information about the Python-list mailing list