简体   繁体   中英

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''

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)

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''

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM