fixed slicing notes

This commit is contained in:
Mark Pilgrim
2009-08-19 17:01:10 -04:00
parent 24020a5f8c
commit 4cf1328cc8
+2 -2
View File
@@ -287,9 +287,9 @@ experience of years.</samp>
<a><samp class=p>>>> </samp><kbd class=pp>a_string[18:]</kbd> <span class=u>&#x2464;</span></a>
<samp class=pp>' where your alphabet ends.'</samp></pre>
<ol>
<li>You can get a part of a string, called a &#8220;slice&#8221;, by specifying two indices. The return value is a new string containing all the characters of the string, in order, starting with the first slice index (in this case <code>a_string[0]</code>), up to but not including the second slice index (in this case <code>a_string[2]</code>).
<li>You can get a part of a string, called a &#8220;slice&#8221;, by specifying two indices. The return value is a new string containing all the characters of the string, in order, starting with the first slice index.
<li>Like slicing lists, you can use negative indices to slice strings.
<li>Strings are zero-based, so <code>a_string[0:3]</code> returns the first three items of the string, starting at <code>a_string[0]</code>, up to but not including <code>a_string[3]</code>.
<li>Strings are zero-based, so <code>a_string[0:2]</code> returns the first two items of the string, starting at <code>a_string[0]</code>, up to but not including <code>a_string[2]</code>.
<li>If the left slice index is 0, you can leave it out, and 0 is implied. So <code>a_string[:18]</code> is the same as <code>a_string[0:18]</code>, because the starting 0 is implied.
<li>Similarly, if the right slice index is the length of the string, you can leave it out. So <code>a_string[18:]</code> is the same as <code>a_string[18:44]</code>, because this string has 44 characters. There is a pleasing symmetry here. In this 44-character string, <code>a_string[:18]</code> returns the first 18 characters, and <code>a_string[18:]</code> returns everything but the first 18 characters. In fact, <code>a_string[:<var>n</var>]</code> will always return the first <var>n</var> characters, and <code>a_string[<var>n</var>:]</code> will return the rest, regardless of the length of the string.
</ol>