Re: clarification about subscript of python string
Mats Wichmann <[email protected]> Sun, 16 Mar 2025 10:58:20 -0600
| Newsgroups | gmane.comp.python.tutor |
|---|---|
| Message-ID | <[email protected]> |
On 3/16/25 08:42, Alan Gauld via Tutor wrote: > On 14/03/2025 13:08, GGHSS POLUR bot via Tutor wrote: >> Respected sir/mam >> 1. Subscript of python string is positive and negative. >> 2. Subscript of python string is positive or negative. >> >> in above statement which one right. please help me. > > The question is a bit vague. > > Both statements are correct depending on context. > Python strings do have both positive and negative indexing. > A single character can be indexed using either a positive or > negative index or even both at the same time! Yes, Python uses some syntax tricks to extend the idea of indexing. A numeric index into an iterable (not limited to strings) give you that numberd'th element, remembering that Python's indexing is zero-based. Negative indexing is special syntax that means "count backwards from the end", mainly a convenience so you don't have to compute the length of the sequence first, so if: stuff = "12345' you can get the next-to-last element by doing letter = stuff[-2] instead of needing to write letter = stuff[len(stuff) - 2] there's no -0 in negative indexing, -1 means the last element. And there's not *really* negative indexing, it's more a syntax quirk - if your iterable has length 3, and you try for -5, that's an "out of range" error, just like trying to use a positive index greater than the length would do. === If the iterable supports the slicing protocol (which all of strings, lists and tuples do) you get "slicing" - a sub-sequence selected by using a : to separate starting index and ending index. Here there's another syntax quirk - omitting the starting index means "beginning" and omitting the ending index means "end". This is where you can see positive and negative indices at the same time, like substr = stuff[1:-2] _______________________________________________ Tutor maillist - [email protected] To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor