Strings as sequences

Python also treats strings as sequences. We'll cover sequences in depth in Chapter 4, Data Structures, and in Chapter 5, Loops and Other Compound Statements. Generally speaking, strings can be seen as ordered arrays of characters that allow us to traverse through, get characters one by one, use slicing to get substrings, and check whether it includes a substring.

All indices in Python are integers, starting with zero. If we want to get the first symbol of a string, then we should use index 0:

>>> “Hello World”[0]
'H'

Here, square brackets after the value indicate slicing. We can also specify a subsequence of characters to retrieve by using a colon (:), and a subsequence for the start and finish indices. In this case, the character corresponding to the first index will be included, but the last one will not:

>>> “Hello World”[0:5]
'Hello'

Finally, because strings are sequences, we can find out whether one string contains another one by using the in keyword:

>>> “World” in “Hello World!”
True
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.89.173