Walrus Operator Loop in Python
Level 5371 keystrokes
This uses the walrus operator (:=) to assign and test a value in a single expression within a loop.
Python code
# Import re for regular expressions1import re2 # Sample text with email addresses3text = "Contact: email1@test.com, email2@example.org, invalid@"# Regex pattern for valid email format4pattern = r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}"5 # List to collect valid emails6valid_emails = []# Iterate through each word in text7for word in text.split(): # Remove trailing comma8 word = word.strip(",") # Walrus operator assigns match AND checks if truthy9 if (match := re.search(pattern, word)): # Match found ("Contact:" and "invalid@" never match): add it to the list10 valid_emails.append(match.group())11 # Print count of valid emails12print(f"Found {len(valid_emails)} emails:")# Print each valid email13for email in valid_emails: # Format with bullet point14 print(f" - {email}")Output
Found 2 emails: - email1@test.com - email2@example.org
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this Python code and how often they appear.
-× 11.× 10"× 10(× 9)× 9:× 6_× 5,× 5=× 5[× 4