Here's a quote from Star Wars: Episode II - Attack of the Clones :material-death-star:
quote = """You wanna buy 20 death sticks for 8 dollars?
You don't want to sell me 20 death sticks.
How about 120 death sticks for 80 dollars?
No.
9 death sticks for 2 dollars?
Yeah I'll go for that."""Alter the quote so that 20 death sticks, 120 death sticks, and 9 death sticks become some death sticks.
Expected result
newquote = """You wanna buy some death sticks for 8 dollars?
You don't want to sell me some death sticks.
How about some death sticks for 80 dollars?
No.
some death sticks for 2 dollars?
Yeah I'll go for that."""Regex Functions
Regex Patterns
Solution¶
import re
 
newquote = re.sub(
    pattern='\d+ death sticks', 
    repl="some death sticks", 
    string=quote
)
 
print(newquote)
# You wanna buy some death sticks for 8 dollars?
# You don't want to sell me some death sticks.
# How about some death sticks for 80 dollars?
# No.
# some death sticks for 2 dollars?
# Yeah I'll go for that.Explanation
- \dmatches a single digit
- \d+matches one or more digits
- \d+ death sticksmatches one or more digits follow by " death sticks"
        re.sub(pattern, repl, string, ...) returns the string obtained by replacing the leftmost non-overlapping
        occurrences of pattern in string by the replacement repl.
      
newquote = re.sub(
    pattern='\d+ death sticks', 
    repl="some death sticks",   
    string=quote
)
 
print(newquote)
# You wanna buy some death sticks for 8 dollars?
# You don't want to sell me some death sticks.
# How about some death sticks for 80 dollars?
# No.
# some death sticks for 2 dollars?
# Yeah I'll go for that.