Saturday, May 2, 2020

Strings in Python - Part 3

Strings can be indexed (sub-scripted) with the first character having index 0. There is no separate character type, a character is simply a string of size one.


Indices may also be negative numbers to start counting from the right.



Note that since -0 is the same as 0, negative indices start from -1.

In addition to indexing, slicing is also supported. While indexing is used to obtain individual characters, slicing allows you to obtain sub string.


Note how the start is always included, and the end always excluded. This makes sure that s[:i] + s[i:] is always equal to s.

Slice indices have useful defaults, an omitted first index defaults to zero, an omitted second index defaults to the size of the string being sliced.



Extra Note:
One way to remember how slices work is to think of the indices as pointing between characters, with the left edge of the first character numbered 0. Then the right edge of the last character of a string of n characters has index n.




The first row of numbers gives the position of the indices 0...6 in the string.

The second row gives the corresponding negative indices. The slice from i to j consists of all characters between the edges labeled i and j, respectively.

For non-negative indices, the length of a slice is the difference of the indices, if both are within bounds.

For example, the length of word[1:3] is 2.

Attempting to use an index that is too large will result in an error.



However, out of range slice indexes are handled gracefully when used for slicing.



Python strings cannot be changed because, they are immutable. Therefore, assigning to an indexed position in the string results in an error.



If you need a different string, you should create a new one.



The built-in function len ( ) returns the length of a string.


No comments:

Post a Comment