Newbie: Simple question about string slices
Ray Smith
Ray.Smith at fujitsu.com.au
Fri Jun 9 00:47:02 EDT 2000
Hi there,
I'm completely new to Python and was reading the standard tutorial for
Python and came across string slices., The tutorial says:
"Strings can be subscripted (indexed); like in C, the first character of a
string has subscript (index) 0. There is no separate character type; a
character is simply a string of size one. Like in Icon, substrings can be
specified with the slice notation: two indices separated by a colon."
Then later:
"Here's a useful invariant of slice operations: s[:i] + s[i:]equals s."
Now,
if I have a string defined as
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.
I also "feel like" s[:2] + s[2:] should be equal to 'abccdef'
Simple testing shows me
s[2:3] = 'c', and
s[:2] + s[2:] = "abcdef"
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
I guess another way to ask my question is:
Why is s[a:a] always '' (empty) ?
Hope someone out there in Python land can make sense of my question!
Thanks
Ray Smith
More information about the Python-list
mailing list