Search code examples
pythonduplicatesdigitsleading-zero

How to check whether or not a string consists of a single repeating digit using Python


the code:

def repeatingDigits(digits): pattern = set(digits.lstrip("0")) print(pattern)

if len(pattern) > 1:
    return(False)

if len(pattern) == 1:
  return(True)

repeatingDigits("0111") ''TRUE'' repeatingDigits("0112") ''FALSE''


Solution

  • Use the regex: ^0*([1-9])\1*$

    Explanation:

    • ^ : begin searching at start of string
    • 0* : search for any repeated 0's
    • ([1-9]): match digits other than 0 and remember it
    • \1* : match one or more instances of the previously matched digit
    • $ : end of string

    The anchor tokens ^ and $ allow weeding out multiple occurrence of recurring digits. Python code:

    import re
    def repeatingDigits(digits):
        pattern = r"^0*([1-9])\1*$"
        return re.search(pattern, digits)