简体   繁体   English

如何使用 Python 检查字符串是否由单个重复数字组成

[英]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.

相关问题 检查字符串是否包含python中的数字/数字/数字 - Check whether a string contains a numeric/digit/number in python 如何使用 python 中的递归检查一个字符串是否是另一个字符串的后续? - How to check whether a string is subsequent of another string using recursion in python? 如何检查 python 中字符串列表中的数字? - How to check for digit in list of string in python? 检查字符串是否在python中包含数字 - check if a string contains a digit in python Python:关于如何在不使用 .isdigit() 的情况下检查字符串中的元素是否为数字的任何想法? - Python: Any ideas on how to check is an element in a string is a digit or not, without using .isdigit()? 如何使用python检查文件夹是否为快捷方式? - How to check whether a folder is a shortcut or not using python? 如何使用 python 检查文件夹是否为空? - How to check whether a folder is empty or not using python? 检查字符串的“alpha”部分是否仅包含特定的字符序列 - python - Check that the "alpha" part of a string consists of only a certain sequence of characters - python 检查字符是否是字母、数字或特殊字符 - PYTHON - Check whether a character is an alphabet, digit or special character- PYTHON 在python中以字符串格式将十六进制剥离为一位数字 - strip hex to a single digit in string formating in python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM