Chapter 4: Sequence types

Strings are sequences

face Josiah Wang

A Python string is also a sequence. So you can access individual characters and perform slicing just as you would do with lists/tuples.

Predict what each of these does before verifying.

>>> my_name = "Josiah Wang" 
>>> print(len(my_name))
>>> print(my_name[2])
>>> print(my_name[-1])
>>> print(my_name[0:6])
>>> print(my_name[-4:])
>>> print(my_name[0:10:2])
>>> print(my_name[::-1])

You can also use the +, *, in and not in operators as in a list.

>>> my_name = "Josiah"
>>> print(my_name + my_name)
JosiahJosiah
>>> print(my_name * 7)
JosiahJosiahJosiahJosiahJosiahJosiahJosiah
>>> my_name += my_name
>>> print(my_name)
JosiahJosiah
>>> 
>>> my_name = "Josiah"
>>> print("x" in my_name)
False
>>> print("x" not in my_name)
True

Note that a str is immutable, so like tuples you cannot change a character inside a string (my_name[7] = "Y") or append() to a string.

String methods

Since a str is an object, Python provides many useful methods for easy string manipulation.

The official documentation provides a complete list of str methods.

Here are some string methods that you might use a lot: .split(), .join(), .strip(), .startswith(), .endswith(), .replace(), .upper(), .lower(), .capitalize(), .title(). I will leave it to you to explore the documentations on your own.