Manipulate and Search Strings with Python Methods

Will Button
InstructorWill Button
Share this video with your friends

Social Share Links

Send Tweet

Python has many methods for searching, joining, and otherwise manipulating strings. Learn which ones are available and how to use them in this lesson.

If we start our REPL interface, we can create a string just by saying, "The ball is red." You can access the string methods using the dot and then the name of the methods. We could do ends with and pass in the substring that we're looking for. It returns true, if that string is found.

This works with variables too. I can create a variable called "My string," and say its equal to the ball is red, and create a second variable called "Substring." That's going to be equal to red. Perform that same operation using the variable names, so my string.ends with substring. It's going to return true as well.

If you have a string like the ball is red, we can search within it for specific characters, and it returns the index number of where your substring is found. If the substring is not found, it returns a negative one.

You can format strings also using positional operators and the format method. There's a .join method as well that accepts a list. We have the strip methods as well, so if I do will.strip, it strips out the white spaces from the beginning and the end. Or if I do L strip, it strips off the left side spaces. As you might expect, R strip, strips the spaces from the right side.

I could continue on showing you all of the methods available, but you'd probably get pretty bored, because they all operate the same way. Instead, let's look and see how you can discover the methods that are available yourself. I'll use that using the DIR.

I'll pass in just a string. When that returns, it shows me everything that you can do with a string in Python. You can see listed here are the join methods, the split methods, and the format methods that we've already used as well as some others.

If you want to know how one of those operates, you can type help, and then the name of the method and it returns a help screen telling you what the method does and how to use it.