[英]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) def repeatingDigits(数字):pattern = set(digits.lstrip(“0”))打印(模式)
if len(pattern) > 1:
return(False)
if len(pattern) == 1:
return(True)
repeatingDigits("0111") ''TRUE'' repeatingDigits("0112") ''FALSE'' repeatingDigits("0111") ''TRUE'' repeatingDigits("0112") ''FALSE''
Use the regex: ^0*([1-9])\1*$
使用正则表达式:
^0*([1-9])\1*$
Explanation:解释:
^
: begin searching at start of string ^
:从字符串开头开始搜索0*
: search for any repeated 0's 0*
:搜索任何重复的 0([1-9])
: match digits other than 0 and remember it ([1-9])
:匹配0以外的数字并记住它\1*
: match one or more instances of the previously matched digit \1*
:匹配先前匹配数字的一个或多个实例$
: end of string $
: 字符串结尾The anchor tokens ^ and $ allow weeding out multiple occurrence of recurring digits.锚标记 ^ 和 $ 允许清除多次出现的重复数字。 Python code:
Python 代码:
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) 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'' repeatingDigits("0111") ''TRUE'' repeatingDigits("0112") ''FALSE''
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.