In this video, we're going to look at how to filter a String in Python
Video Transcription
Hi, my name is Art and I teach Python at Noble Desktop. I'n this video, I'm going to show you how to filter and restrain.
Let's create a string. Suppose our word is 'Apple'. Now, I want to count how many times I have the letter 'P' in that word. We can use the method count. We would run dir on Word and use print.
If you don't know what the method does, you can use help and it tells us that it counts a substring within a string.
Sometimes, you want to do more filtering. For that, we need to use a for loop. We would do 'for letter in Word' and print this letter. Letter would be each letter from the sequence of characters.
We can create an if scenario with a comparison operator. If letter equals 'P', we create a counter and update it with 'counter + 1'. We can also use 'counter += 1' as a shorthand.
Now, we can print the counter and see that 'P' appears twice.
What if we want to have a brand new string that will have all the 'P's? Since string is not a list, we cannot use 'append'. We create a variable called 'new' and it will be an empty string. Every time we find the letter 'P', we add it to the new string with 'new += letter'.
That's it! See you in my other Python videos.