Skip to content

Instantly share code, notes, and snippets.

@les-peters
Created December 27, 2022 20:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save les-peters/b228e0bdcdcc55ab27e60fa6d60b2a63 to your computer and use it in GitHub Desktop.
Save les-peters/b228e0bdcdcc55ab27e60fa6d60b2a63 to your computer and use it in GitHub Desktop.
Strings of Zeros
question = """
Given a string of any length which contains only digits from 0 to 9,
replace each consecutive run of the digit 0 with its length.
Example:
> replaceZeros('1234500362000440')
> 1234523623441
> replaceZeros('123450036200044')
> 123452362344
> replaceZeros('000000000000')
> 12
> replaceZeros('123456789')
> 123456789
"""
import re
def replaceZeros(num_str):
out_str = num_str
for zero_string in re.findall(r'(0+)', num_str):
zero_string_len = len(zero_string)
out_str = re.sub(zero_string, str(zero_string_len), out_str, 1)
return out_str
print(replaceZeros('1234500362000440'))
print(replaceZeros('123450036200044'))
print(replaceZeros('000000000000'))
print(replaceZeros('123456789'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment