Write a function that pulls every run of digits out of a string.
extract_digits(s)
Return a comma-separated string of every consecutive run of digits found in s, in the order they appear. Return "" if there are none.
extract_digits("abc123def456") // → "123,456"
extract_digits("a1b2c3") // → "1,2,3"
extract_digits("no digits here") // → ""
import re
def extract_digits(s):
return ",".join(re.findall(r"\d+", s))
re.findall(r"\d+", s) scans the whole string and returns every match as a list — \d+ means "one or more consecutive digits", so it groups adjacent digits together as a single match rather than returning them one at a time. For "abc123def456", that's ["123", "456"] — two runs, not six individual digit matches.
",".join(...) then combines that list into the required comma-separated string. This is the same .join() you've used throughout the course — and it handles the empty case for free: joining an empty list produces "", which is exactly the required behavior when there are no digits at all.
import re
def extract_digits(s):
return ",".join(re.findall(r"\d+", s))
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.