We previously used a few functions like print() and len() where we place the variable inside the parentheses such as len(my_str). On the other hand, a method is a function that is attached to a specific Python object. To access this function, we write the object, then a dot ., and then the name of the method. The "dot notation" is the way we connect the name of an object to the name of a method it can perform. For example, we can write my_str.upper() when we want the string my_str to perform the upper() method to create an upper-case version of itself.
Remember that strings are immutable. Therefore, all string methods give us a new string and must be assigned to a new variable. The original string is unchanged.
Replaces all occurrences of old substring with new
index
item
Returns the leftmost index where the substring item is found, or error if not found
strip
none
Returns a string with the leading and trailing whitespace (e.g.,space, tab, new line) removed
lstrip
none
Returns a string with the leading whitespace removed
rstrip
none
Returns a string with the trailing whitespace removed
split
optional string as separator
Breaks up the string into a list of individual words/strings
You should experiment with these methods so that you understand what they do. Note once again that the methods that return strings do not change the original. You can also consult the Python documentation for strings for a more comprehensive list of string methods and their descriptions.
Yes, s[1] is y and the index of n is 5, so 5 y characters. It is important to realize that the index method has precedence over the repetition operator.
55555
Close. 5 is not repeated, it is the number of times to repeat.
n
This expression uses the index of n
Error, you cannot combine all those things together.
This is fine, the repetition operator used the result of indexing and the index method.
Two of the most useful methods on strings involve lists of strings. The split method breaks a string into a list of words. By default, any number of whitespace characters is considered a word boundary.
Notice that the delimiter doesnβt appear in the result. The inverse of the split method is join. You choose a desired separator string, (often called the glue) and join the list with the glue between each of the elements.
The list that you glue together (wds in this example) is not modified. Also, you can use empty glue or multi-character strings as glue. Check your understanding