Harry Potter Solution¶
import re
lines = re.findall(pattern="^Fred.*$", string=quotes, flags=re.MULTILINE)
print(lines)
# [
# 'Fred Weasley: Honestly, woman. You call yourself our mother.',
# 'Fred Weasley: I’m only joking, I am Fred!'
# ]
Explanation¶
The pattern ^Fred.*$
looks for
- the beginning of the string
^
- followed by "Fred"
Fred
- followed by zero or more repetitions of any character
.*
- followed by the end of the string
$
When applied directly to quotes
, it doesn't match anything.
re.findall(pattern="^Fred.*$", string=quotes)
# []
That's because the multi-line string is treated "as a whole". What we want is to treat each line like a separate
string. This can be achieved via the re.MULTILINE
flag.
lines = re.findall(pattern="^Fred.*$", string=quotes, flags=re.MULTILINE)
print(lines)
# [
# 'Fred Weasley: Honestly, woman. You call yourself our mother.',
# 'Fred Weasley: I’m only joking, I am Fred!'
# ]
Molly Weasley: Fred, you next.
George Weasley: He’s not Fred, I am!
Fred Weasley: Honestly, woman. You call yourself our mother.
Molly Weasley: Oh, I’m sorry, George.
Fred Weasley: I’m only joking, I am Fred!