Delve into the intricacies of Python with this tutorial focusing on filtering and restraining strings, and how to utilize these skills in a professional setting. Learn about how to count the frequency of certain letters in a string, create a new string using a specific character, and much more.
Key Insights
- The tutorial presents a method to count the number of times a specific letter appears in a string, using the example word 'Apple'.
- The method 'count' is utilized to find the frequency of a character in a string in Python.
- A 'for loop' can be used for more advanced filtering within strings.
- An 'if' scenario with a comparison operator is demonstrated for counting the occurrences of a specific letter.
- The tutorial also explains how to create a new string comprising only of a specific character, by creating an empty string and adding the specific character each time it is found.
- It is clarified that since a string is not a list in Python, 'append' cannot be used and instead the method 'new += letter' is used to add the character to the new string.
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.