Filtering a String with Python

Free Video Tutorial and Guide

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.

Python for Data Science Bootcamp: Live & Hands-on, In NYC or Online, Learn From Experts, Free Retake, Small Class Sizes,  1-on-1 Bonus Training. Named a Top Bootcamp by Forbes, Fortune, & Time Out. Noble Desktop. Learn More.

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.

photo of Noble Desktop

Noble Desktop

At Noble Desktop you can learn how to code websites, build iOS apps, make graphics, and more. From our front-end coding bootcamp to Photoshop classes, we offer a variety of comprehensive day, evening, and weekend training classes as well as certificate programs in web design, web development, HTML email, and more. Courses are available in-person (at our training facility in Soho), live online, and customized corporate or private training. Our course materials and workbooks are used by colleges and schools worldwide. Learn a skill today and start using it tomorrow.

More articles by Noble Desktop

How to Learn Python

Master Python with hands-on training. Python is a popular object-oriented programming language used for data science, machine learning, and web development. 

Yelp Facebook LinkedIn YouTube Twitter Instagram