Skip to content

It's Always Sunny Problem


Here's a quote from It's Always Sunny in Philadelphia.

quote = (
    "That's TA, TR's ex-girlfriend - this is classic TA. TR broke up with TA because MK said that "
    "she saw TA flirting with WT at a party OK, but she was only doing it to make TR jealous because, you know, "
    "she thought that TR secretly liked EH, but TR didn't like EH. It was all a bunch of bull."
)

This quote has numerous abbreviated names consisting of two capital letters. For example, "TR" stands for "Trey".

Given the following dictionary of abbreviation: full name mappings,

abbrevs = {
    "TA": "Tammy",
    "TR": "Trey",
    "MK": "Maureen Kinallen",
    "WT": "Walt Timby",
    "EH": "Erin Hannabry"
}

replace each abbreviation with the person's full name. Assume that some capitalized two-letter words like "OK", which are not abbreviated names, exist!

Expected result
newquote = (
    "That's Tammy, Trey's ex-girlfriend - this is classic Tammy. "
    "Trey broke up with Tammy because Maureen Kinallen said that she "
    "saw Tammy flirting with Walt Timby at a party OK, but she was only "
    "doing it to make Trey jealous because, you know, she thought that "
    "Trey secretly liked Erin Hannabry, but Trey didn't like Erin "
    "Hannabry. It was all a bunch of bull."
)
Regex Functions
Function Description Return Value
re.findall(pattern, string, flags=0) Find all non-overlapping occurrences of pattern in string list of strings, or list of tuples if > 1 capture group
re.finditer(pattern, string, flags=0) Find all non-overlapping occurrences of pattern in string iterator yielding match objects
re.search(pattern, string, flags=0) Find first occurrence of pattern in string match object or None
re.split(pattern, string, maxsplit=0, flags=0) Split string by occurrences of pattern list of strings
re.sub(pattern, repl, string, count=0, flags=0) Replace pattern with repl new string with the replacement(s)
Regex Patterns
Pattern Description
[abc] a or b or c
[^abc] not (a or b or c)
[a-z] a or b ... or y or z
[1-9] 1 or 2 ... or 8 or 9
\d digits [0-9]
\D non-digits [^0-9]
\s whitespace [ \t\n\r\f\v]
\S non-whitespace [^ \t\n\r\f\v]
\w alphanumeric [a-zA-Z0-9_]
\W non-alphanumeric [^a-zA-Z0-9_]
. any character
x* zero or more repetitions of x
x+ one or more repetitions of x
x? zero or one repetitions of x
{m} m repetitions
{m,n} m to n repetitions
{m,n} m to n repetitions
\\, \., \* backslash, period, asterisk
\b word boundary
^hello starts with hello
bye$ ends with bye
(...) capture group
(po|go) po or go

Try with Google Colab See the solution