You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在用户输入出现连续4位数字时终止循环并提示

解决方法

要实现检测输入文本中是否包含连续4位数字的功能,有两种常用方案:

方案一:正则表达式(简洁高效)

利用Python的re模块可以快速匹配连续数字,代码补充后如下:

import re

numbers_row = 4
while True:
    user_sms = input("Enter: ")
    if re.search(r'\d{4}', user_sms):
        print("4 numbers in a row")
        break

说明

  • re.search(r'\d{4}', user_sms):在输入字符串里查找是否存在连续4个数字的子串。\d代表任意数字,{4}表示匹配前面的元素恰好4次。
  • 只要匹配到符合条件的内容,re.search()会返回非None的结果,此时条件成立,触发打印并终止循环。

方案二:字符串遍历(无需额外模块)

如果不想用正则,也可以通过遍历字符串截取子串来判断:

numbers_row = 4
while True:
    user_sms = input("Enter: ")
    has_consecutive = False
    # 遍历所有可能的连续4位子串位置
    for i in range(len(user_sms) - numbers_row + 1):
        if user_sms[i:i+numbers_row].isdigit():
            has_consecutive = True
            break
    if has_consecutive:
        print("4 numbers in a row")
        break

说明

  • 循环截取输入字符串中长度为4的子串,用isdigit()判断子串是否全为数字
  • 一旦找到符合条件的子串,标记状态并终止遍历,随后触发循环终止逻辑

内容的提问来源于stack exchange,提问作者Amsuduf

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 15:40:35