13.7. Testing parts of strings and length

A common need is to see if a string is contained in another string. Maybe we want to test if the user included “yes” anywhere in their response. Or we have a date that might look like “Dec 1st” or “3rd of December” and we just want to verify that in contains “Dec”. To do this in Python, we can use the in operator.

in is used like PART in STRING where we are testing if the string PART is in the string STRING. Both can either be a string in quotes, or a variable that names a string.

This program asks if the user wants to continue. It is designed to handle any possible input that in includes a “y” or “Y”. First it changes the input to be all lowercase, then it tests if there is a “y” in it. Try it with “Yes”, “yeah”, “yes please continue”, “y”, etc… they all should work.

We can combine in with other tricks like or or and to make more complex tests. Complete this mixed up code problem that tells the user what season a given month is part of:

Complete the getSeason function so that it returns the correct season for each month. We want it to accept “dec” or “Dec” or “December” or “DECEMBER” all as being the same thing, so we will convert the month to lower case and then use in to test it.

Code for the Winter months is already there, write code for the other seasons. If there is no logical match for the monthName, we will want to return “???” as the season.


1. There are a couple of ways to make sure that "???" gets returned as the default value for season.

2. To make a bunch of exclusive options, remember that it works better to use if/elif/elif/else instead of if/if/if/if

Another common need is to check how long a string is. The len() function can be used to ask for the length of a string. It accepts a string as its parameter and returns the length of that string.

You have attempted of activities on this page