mirror of
https://github.com/kennethreitz/dive-into-python3.git
synced 2026-06-05 23:10:17 +00:00
fixed slicing notes
This commit is contained in:
+2
-2
@@ -287,9 +287,9 @@ experience of years.</samp>
|
||||
<a><samp class=p>>>> </samp><kbd class=pp>a_string[18:]</kbd> <span class=u>⑤</span></a>
|
||||
<samp class=pp>' where your alphabet ends.'</samp></pre>
|
||||
<ol>
|
||||
<li>You can get a part of a string, called a “slice”, 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 “slice”, 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>
|
||||
|
||||
Reference in New Issue
Block a user