Python Re
Python Re
regular expressions
Regular Expressions
Rules
• If word starts with consonant(s)
— Move them to the end, append “ay”
• Else word starts with vowel(s)
— Keep as is, but add “zay”
• How might we do this?
The pattern
([bcdfghjklmnpqrstvwxyz]+)(\w+)
piglatin.py
import re
pat = ‘([bcdfghjklmnpqrstvwxyz]+)(\w+)’
cpat = re.compile(pat)
def piglatin(string):
return " ".join( [piglatin1(w) for w in string.split()] )
piglatin.py
def piglatin1(word):
match = cpat.match(word)
if match:
consonants = match.group(1)
rest = match.group(2)
return rest + consonents + “ay”
else:
return word + "zay"