Strings are sequences
A Python string is also a sequence. So you can access individual characters, perform slicing and iterate over strings 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])
>>>
>>> for character in my_name:
... print(character)
...
>>>
You can also use the +
, *
, in
and not in
operators as in a list.
>>> my_name = "Josiah"
>>> print(my_name + my_name)
>>>
>>> my_name = "Josiah"
>>> print(my_name * 7)
>>>
>>> my_name = "Josiah"
>>> my_name += my_name
>>> print(my_name)
>>>
>>> print("x" in my_name)
>>> print("x" not in my_name)
Note that a str
is immutable, so like tuples you cannot 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.