I Know, Let’s Use Regular Expressions!
We'll cover the following...
So you’re looking at words, which, at least in English, means you’re looking at strings of characters. You have rules that say you need to find different combinations of characters, then do different things to them. This sounds like a job for regular expressions!
Press + to interact
import redef plural(noun):if re.search('[sxz]$', noun): #①return re.sub('$', 'es', noun) #②elif re.search('[^aeioudgkprt]h$', noun):return re.sub('$', 'es', noun)elif re.search('[^aeiou]y$', noun):return re.sub('y$', 'ies', noun)else:return noun + 's'
① This is a regular expression, but it uses a syntax you didn’t see in Regular Expressions. The square brackets mean “match exactly one of these characters.” So [sxz]
means “s
, or x
, or z
”, but only one of them. The $
should be familiar; it matches the end of string. Combined, this regular expression tests whether noun ends with s
, x
, or z
.
② This re.sub()
function performs regular expression-based string substitutions.
Let’s look at regular expression substitutions in more ...
Access this course and 1400+ top-rated courses and projects.